package com.thinkTank.oa.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.common.UserInfo;
import com.thinkTank.oa.configuration.Log;
import com.thinkTank.oa.configuration.RefPid;
import com.thinkTank.oa.entity.ButtDetails;
import com.thinkTank.oa.entity.ConfOfAttr;
import com.thinkTank.oa.entity.Conference;
import com.thinkTank.oa.entity.Customer;
import com.thinkTank.oa.entity.Demand;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Project;
import com.thinkTank.oa.entity.Subscribe;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.lucene.IsolrOperation;
import com.thinkTank.oa.lucene.LuceneCustomer;
import com.thinkTank.oa.lucene.LucenePerson;
import com.thinkTank.oa.lucene.LuceneProject;
import com.thinkTank.oa.lucene.Pagination;
import com.thinkTank.oa.lucene.SolrOperation;
import com.thinkTank.oa.service.ConOfAttrService;
import com.thinkTank.oa.service.ConferenceService;
import com.thinkTank.oa.service.CustomerService;
import com.thinkTank.oa.service.DemandService;
import com.thinkTank.oa.service.DetailsService;
import com.thinkTank.oa.service.DictiontryService;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.service.ProjectService;
import com.thinkTank.oa.service.SubscribeService;
import com.thinkTank.oa.util.ExcelUtil;
import com.thinkTank.oa.util.FileUtils;
import com.thinkTank.oa.util.StrUtil;

@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(CustomerController.class);

	@Resource
	private CustomerService customerService;

	@Resource
	private ConferenceService conferenceService;

	@Resource
	private ConOfAttrService conOfAttrService;

	@Resource
	private DictiontryService dictiontryService;

	@Resource
	private PersonService personService;

	@Resource
	private ProjectService projectService;

	@Resource
	private DemandService demandService;

	@Resource
	private DetailsService detailsService;
	
	@Autowired
	private SubscribeService subscribeService;

	/** 将常用的list封装到Model中 */
	private void addListToModel(Model model) {
		/**
		 * 用于修改页面的回显
		 */
		// 获取客户来源
		List<Dictiontry> customerSourceList = getCustomerSource();
		// 专家来源
		List<Dictiontry> sourceList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_PROJECTSOURCE);
		// 获取客户类型
		List<Dictiontry> customerTypeList = getCustomerType();
		// 项目来源
		List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所属领域
		List<Dictiontry> researchFieldDictiontryList = getResearchField();
		// 客户性质
		List<Dictiontry> customerNatureList = getCustomerNature();
		// 专家类型
		List<Dictiontry> personTypeList = getPersonType();
		// 需求类型demandType
		List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
		// 需求状态
		List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);
		// 人才级别
		List<Dictiontry> talentLevelListByDic = getTalentLevel();
		// 获取意向合作方式
		List<Dictiontry> intentionCooperateList = getIntentionCooperate();
		// 获取意向合作方式2
		List<Dictiontry> intentionCooperateList2 = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_INTENTIONCOOPERATE2);
		// 获取意向合作状态
		List<Dictiontry> currentStateList = getCurrentState();
		// 所有国家
		List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
		// 项目类型
		List<Dictiontry> projectTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTTYPE);
		model.addAttribute("countryDictiontryList", countryDictiontryList);
		model.addAttribute("projectTypeDictiontryList", projectTypeDictiontryList);

		model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
		model.addAttribute("intentionCooperateList2", intentionCooperateList2);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("demandStatusDictiontryList", demandStatusDictiontryList);
		model.addAttribute("demandTypeDictiontryList", demandTypeDictiontryList);
		model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
		model.addAttribute("personTypeList", personTypeList);
		model.addAttribute("talentLevelListByDic", talentLevelListByDic);
		model.addAttribute("customerSourceList", customerSourceList);
		model.addAttribute("customerTypeList", customerTypeList);
		model.addAttribute("customerNatureList", customerNatureList);
		model.addAttribute("sourceList", sourceList);

		model.addAttribute("intentionCooperateList", intentionCooperateList);
		model.addAttribute("currentStateList", currentStateList);
	}

	/**
	 * 会议活动列表展示数据来源
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/customerList")
	public String customerList(Customer customer, BindingResult bindingResult, Integer pageNum, Model model,
			@RequestParam(value = "customerNumberId", required = false) String customerNumberId,HttpServletRequest request) {

		String cityId = "";
		String province = "";
		
		//通过pid查询用户
	    User user = userService.findUserById(customer.getCollectPersonId());

		if (StringUtil.isNotEmpty(customer.getArea()) && customer.getDomesticOrForeign() != null) {
			areaModel(model, customer.getArea(), customer.getDomesticOrForeign());
		}

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		addListToModel(model);
		String customerNum = "";
		if (StringUtil.isNotEmpty(customer.getMajorNeeds())) {
			customer.setMajorNeeds(customer.getMajorNeeds().trim());
		}

		if (StringUtil.isNotEmpty(customer.getCustomerName())) {
			customer.setCustomerName(customer.getCustomerName().trim());
		}
		// 重新复制客户id
		if (StringUtil.isNotEmpty(customerNumberId)) {
			customerNum = String.valueOf(customerNumberId.trim());
			// 去除字母
			customerNum = customerNum.replaceAll("[a-zA-Z]", "");
		}

		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(customer.getResearchField())) {
			researchFieldArr = customer.getResearchField().split(",");
			customer.setResearchFieldNumber(researchFieldArr.length);
			customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));
		}
		model.addAttribute("researchFieldArr", researchFieldArr);
		if (StringUtil.isNotEmpty(customerNum)) {
			customer.setCustomerNumber(Integer.parseInt(customerNum));
		}
		
		//根据录入人搜索
		String collecId="";
		if(StringUtil.isNotEmpty(customer.getCollectPersonName())){
			User getuser=userService.getUserByFullname(customer.getCollectPersonName().trim());
			if(getuser!=null){
				collecId=getuser.getPid();
			}else{
				collecId="111";
			}
		}
		customer.setCollectPersonId(collecId);
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		// 查询所有会议活动数据
		List<Customer> customerList = customerService.queryAllCustomer(customer);

		for (int i = 0; i < customerList.size(); i++) {
			String areaStr = "";
			String reachName = "";
			// 得到所属领域二进制
			String rearch = customerList.get(i).getResearchField();
			// 得到areaId
			String areaStrId = String.valueOf(customerList.get(i).getArea());
			if (areaStrId != null && !"".equals(areaStrId) && !"null".equals(areaStrId)) {
				if (areaStrId.length() < 10 && areaStrId.length() > 5 && areaStrId.length() != 4) {
					// 说明是区的id
					// 截取得到省和市的id
					Dictiontry dicArea = new Dictiontry();
					dicArea.setNames(areaStrId);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
					// 区的名字
					// areaStr =
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// cityId = areaStrId.substring(0, 5);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					// dicArea.setNames(cityId);
					// // 市的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// province = areaStrId.substring(0, 2);
					// dicArea.setNames(province);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// // 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";

					areaStr = getAreaWorth(areaStrId, 0);
				}

				if (areaStrId.length() == 4) {
					// 说明是国外的
					Dictiontry dicArea = new Dictiontry();
					dicArea.setPid(Integer.parseInt(areaStrId));
					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 1);
				}
				if (areaStrId.length() < 6 && areaStrId.length() > 2 && areaStrId.length() != 4) {
					// 说明是市的id
					Dictiontry dicArea = new Dictiontry();
					cityId = areaStrId.substring(0, 5);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					dicArea.setNames(cityId);
					// 市的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// province = areaStrId.substring(0, 2);
					// dicArea.setNames(province);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// // 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";
					areaStr = getAreaWorth(areaStrId, 0);

				}

				if (areaStrId.length() < 3 && areaStrId.length() > 0 && areaStrId.length() != 4) {
					// 说明是省的id
					Dictiontry dicArea = new Dictiontry();
					province = areaStrId.substring(0, 2);
					dicArea.setNames(province);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";
					areaStr = getAreaWorth(areaStrId, 0);
				}
			}
			// 给地区附上名字
			customerList.get(i).setAreaNameStr(areaStr);
			// String rearchStr = StrUtil.byteToString(rearch);
			reachName = getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
			
			String personId=customerList.get(i).getCollectPersonId();
			if(StringUtil.isNotEmpty(personId)){
				customerList.get(i).setRemark5(userService.getById(personId).getFullName());
			}
			
			// String[] reaArray = rearchStr.split(",");
			// for (String reaStr : reaArray) {
			// Dictiontry dic = new Dictiontry();
			// dic.setGroupName(Constant.DICTIONTRY_PROJECTFIELD);
			// dic.setNames(reaStr);
			// List<Dictiontry> dicList =
			// dictiontryService.findDictiontryByNamesAndGroupName(dic);
			// for (Dictiontry dictiontry : dicList) {
			// reachName += dictiontry.getWorth() + " ";
			// }
			// }
			customerList.get(i).setResearchFieldNameStr(reachName);
			// 取出当前客户性质
			int customerNatureStr = customerList.get(i).getCustomerNature();
			// 取出当前合作状态
			int currentStateStr = customerList.get(i).getCurrentState();
			customerList.get(i)
					.setCustomerNatureName(getDicSingleWorth(customerNatureStr, Constant.DICTIONTRY_CUSTOMERNATURE));
			customerList.get(i)
					.setCurrentStateName(getDicSingleWorth(currentStateStr, Constant.DICTIONTRY_CURRENTSATUS));
		}

		  //查询已经关注的
        Subscribe subscribe = new Subscribe();
        subscribe.setSubType(3);//关注类型为会议
        subscribe.setUserid(getUserId(request));
        List<Subscribe> subList = subscribeService.queryAll(subscribe);
        List<String> subDemandIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
        model.addAttribute("subDemandIdList", subDemandIdList);

		// 将list放进PageInfo
		PageInfo<Customer> pageInfo = new PageInfo<Customer>(customerList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("user", user);

		// 演讲嘉宾展示List
		return "customerlist";
	}

	/**
	 * 添加客户跳转页面 xyx
	 * 
	 * @param request
	 * @return 2018年8月17日
	 */
	@RequestMapping(value = "/addCustomer")
	public String addCustomer(Model model) {

		if (!model.containsAttribute("customer")) {
			model.addAttribute("customer", new Customer());
		}

		if (!model.containsAttribute("researchFieldArr")) {
			model.addAttribute("researchFieldArr", "");
		}

		addListToModel(model);
		return "addCustomer";
	}

	@RequestMapping(value = "/saveCustomer", method = RequestMethod.POST)
	public String saveCustomer(@Valid Customer customer, BindingResult bindingResult, MultipartFile customerFiles, HttpServletRequest request,
			Model model) {

		// 表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("customer", customer);
				// 获取地区相关数据，便于回显
				String areaId = customer.getArea();
				String cityId = "";
				String province = "";
				if (StringUtil.isNotEmpty(areaId)) {
					if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
						// 说明是区的id
						// 截取得到省和市的id
						cityId = areaId.substring(0, 5);
						province = areaId.substring(0, 2);
						model.addAttribute("areaId", areaId);
						model.addAttribute("cityId", cityId);
						model.addAttribute("province", province);
					}
					if (areaId.length() < 3 && areaId.length() > 0) {
						// 说明是省的id
						model.addAttribute("province", areaId);
					}
					if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
						// 说明是市的id
						// 截取得到省和市的id
						cityId = areaId;
						province = areaId.substring(0, 2);
						model.addAttribute("province", province);
						model.addAttribute("cityId", cityId);
					}

					// 所有市
					List<Dictiontry> cityDictiontryList = getCityByProvince(province);
					// 所有区
					List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

					model.addAttribute("cityDictiontryList", cityDictiontryList);
					model.addAttribute("areaDictiontryList", areaDictiontryList);
				}

				String[] researchFieldArr = null;
				if (StringUtil.isNotEmpty(customer.getResearchField())) {
					researchFieldArr = customer.getResearchField().split(",");
				}
				if (researchFieldArr != null) {
					model.addAttribute("researchFieldArr", researchFieldArr);
				} else {
					model.addAttribute("researchFieldArr", "");
				}
				if (customer.getDomesticOrForeign() != null) {
					if (customer.getDomesticOrForeign() == 1) {
						model.addAttribute("countryId", Integer.parseInt(areaId));
					}
				}
				return addCustomer(model);
			}
		}
		
		if (null != customerFiles && !customerFiles.isEmpty()) {
			// 文件名字
			String fileName = customerFiles.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("customer", fileName);

			customer.setCustomerFile(oldFileName);
			try {
				FileUtils.uploadFile(customerFiles.getBytes(), Constant.DEF_CONF_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}

		// 收集时间
		customer.setEntryTime(StrUtil.getCurrentDateTime());
		// 收集人(录入人) 从session中获取登录账号
		customer.setCollectPersonId(getUserInfoBySession(request).getUserId());

		// 转化为二进制保存
		customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));

		customer.setPid(StrUtil.getUUID32());
		customerService.add(customer);

		LuceneCustomer lucustomer = returnLuceCustomer(customer);
		List<LuceneCustomer> luceneCustomerList = new ArrayList<LuceneCustomer>();
		luceneCustomerList.add(lucustomer);
		IsolrOperation<LuceneCustomer> iso = new SolrOperation<>();
		iso.add("customer", luceneCustomerList);

		// System.out.println("保存成功");
		return "redirect:/customer/customerList";
	}

	@RequestMapping(value = "/updateCustomer")
	public String updateCustomer(@RequestParam("pid") String pid, Model model,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "conferencePid", required = false) String conferencePid) {
		// 根据pid查询到对应的客户数据
		Customer customer = customerService.getById(pid);
		if (!model.containsAttribute("customer")) {
			model.addAttribute("customer", customer);
		}

		String cityId = "";
		String province = "";
		String areaId = String.valueOf(customer.getArea());
		if (areaId.length() < 10 && areaId.length() > 5) {
			// 说明是区的id
			// 截取得到省和市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("areaId", areaId);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}

		if (areaId.length() < 6 && areaId.length() > 2 && areaId.length() != 4) {
			// 说明是市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("province", province);
			model.addAttribute("cityId", cityId);
		}

		if (areaId.length() < 3 && areaId.length() > 0) {
			// 说明是省的id
			model.addAttribute("province", areaId);
		}

		if (customer.getDomesticOrForeign() == 1) {
			model.addAttribute("countryId", Integer.parseInt(areaId));
		}

		// 研究领域二进制转化为字符串
		String researchFieldstr = StrUtil.byteToString(customer.getResearchField());
		String[] researchFieldArr = researchFieldstr.split(",");
		model.addAttribute("researchFieldArr", researchFieldArr);
		// 所有市
		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
		// 所有区
		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

		model.addAttribute("cityDictiontryList", cityDictiontryList);
		model.addAttribute("areaDictiontryList", areaDictiontryList);

		addListToModel(model);
		model.addAttribute("pid", pid);

		model.addAttribute("origType", origType);
		model.addAttribute("conferencePid", conferencePid);

		return "customerupdate";
	}

	/**
	 * 保存修改会议数据
	 * 
	 * @param conference
	 * @param bindingResult
	 * @param conferenceFile
	 * @param customerIds
	 * @param request
	 * @return
	 */
	@Log("修改客户")
	@RequestMapping(value = "/saveUpdateCustomer", method = RequestMethod.POST)
	public String saveUpdateCustomer(
			@RequestParam(value = "customerFiles", required = false) MultipartFile customerFiles,
			@RefPid @Valid Customer customer, BindingResult bindingResult, Model model,@RequestParam(value = "newEvolve", required = false) String newEvolve, HttpServletRequest request,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "conferencePid", required = false) String conferencePid) {

		// 表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("customer", customer);
				return updateCustomer(customer.getPid(), model, null, null);
			}
		}
		
		if (null != customerFiles && !customerFiles.isEmpty()) {
			// 文件名字
			String fileName = customerFiles.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("customer", fileName);

			customer.setCustomerFile(oldFileName);
			try {
				FileUtils.uploadFile(customerFiles.getBytes(), Constant.DEF_CONF_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}else{
			String pid=customer.getPid();
			//修改时，若不上传附件，则不改变原附件路径
			String fileName=customerService.getById(pid).getCustomerFile();
			customer.setCustomerFile(fileName);
		}

		//客户最新进展直接生成一条新记录，保留历史记录
		customer.setEvolve(newEvolve+"   "+customer.getEvolve());
		// 收集人(录入人) 不变
		customer.setCollectPersonId(customerService.getById(customer.getPid()).getCollectPersonId());
		// 收集时间
		customer.setEntryTime(StrUtil.getCurrentDateTime());
		// 转化为二进制保存
		customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));
		// 保存会议活动数据
		customer.setUpdateTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
		customerService.update(customer);

		LuceneCustomer lucustomer = returnLuceCustomer(customer);
		IsolrOperation<LuceneCustomer> iso = new SolrOperation<>();
		iso.update("customer", lucustomer);
		// System.out.println("保存成功");
		if (StringUtil.isNotEmpty(origType)) {
			return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
		} else {
			return "redirect:/customer/showDetail?customerId=" + customer.getPid();
		}
	}

	/**
	 * 添加客户联系人跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addCustomerContact")
	public String addCustomerContact(@RequestParam("pid") String pid, Model model,@RequestParam(value = "personId", required = false) String personId,HttpServletRequest request) {

		if (!model.containsAttribute("person") && !StringUtil.isNotEmpty(personId)) {
			//设置默认值
			Person person=new Person();
			
			person.setDomesticOrForeign(0);
			person.setArea("111011001");
			areaModel(model, person.getArea(), person.getDomesticOrForeign());
			person.setSex(0);
			model.addAttribute("person", person);
		}else{
			Person person=personService.getById(personId);
			areaModel(model, person.getArea(), person.getDomesticOrForeign());
			String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
			model.addAttribute("researchFieldArr", researchFieldArr);
			
			if(person.getTalentLevel()!=null){
				String[] talentLevelArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
				model.addAttribute("talentLevelArr", talentLevelArr);
			}else {
				model.addAttribute("talentLevelArr", "");
			}
			
			model.addAttribute("person", person);
		}

		if (!model.containsAttribute("researchFieldArr")  && !StringUtil.isNotEmpty(personId)) {
			String[] researchFieldArr = StrUtil.byteToString("0000000000000000000000000000000000000000000000000000000000000001").split(",");
			model.addAttribute("researchFieldArr", researchFieldArr);
		}
		if (!model.containsAttribute("talentLevelArr") && !StringUtil.isNotEmpty(personId)) {
			model.addAttribute("talentLevelArr", "");
		}

		addListToModel(model);

		// 客户pid
		model.addAttribute("pid", pid);
		model.addAttribute("collectPersonId", getUserInfoBySession(request).getUserId());
		model.addAttribute("entryTime", StrUtil.getCurrentDateTime());

		return "addCustomerContact";
	}

	/**
	 * 添加客户联系人
	 * 
	 * @param pid
	 * @param name
	 * @param email
	 * @param tell
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/saveCustomerGuest", method = RequestMethod.POST)
	public String saveCustomerGuest(@RequestParam("customerPid") String customerPid, @Valid Person person,
			BindingResult bindingResult, Model model, @RequestParam("annex1") MultipartFile annex1,
			HttpServletRequest request) {

		// 收集人（录入人）
		person.setCollectPersonId(getUserInfoBySession(request).getUserId());
		// 录入时间
		person.setEntryTime(StrUtil.getCurrentDateTime());

		// 前台页面弹出错误信息
		String msg = "";
		// 表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 调用本类方法
				addInfo(person, model);
				model.addAttribute("person", person);
				// 报错就直接返回新增页面
				return addCustomerContact(customerPid, model, "", request);
			}
		}

		// 通过pid查询到相关的客户数据
		Customer customer = customerService.getById(customerPid);
		// 转化为二进制保存
		customer.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		// 获取当前登录信息
		UserInfo userInfo = getUserInfoBySession(request);
		
		// 添加的持有人有电话，微信或者邮箱，就去数据库查这个人
		// 调用董力的接口，返回专家对象
		Person queryPerson = personService.findPersonByInfo(person);
		if (queryPerson == null) {
			// 生成主键id
			String personId = StrUtil.getUUID32();

			// 先新增专家库数据
			person.setPid(personId);
			person.setCollectPersonId(userInfo.getUserId());
			// 将所属领域复选框转换为二进制格式
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
			// 将人才级别复选框转换为二进制格式
			if (StringUtil.isNotEmpty(person.getTalentLevel())) {
				person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
			}
			// 上传附件
			if (null != annex1 && !annex1.isEmpty()) {
				// 文件名字
				String fileName = annex1.getOriginalFilename();
				String oldFileName = FileUtils.generateFileName("conference", fileName);

				person.setAnnex(oldFileName);
				try {
					FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_CONF_PATH, oldFileName);
				} catch (Exception e) {
					logger.error("上传文件失败：" + e.getMessage());
				}
			}
			// 专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
			if (!person.getName().isEmpty()
					&& (!person.getTell().isEmpty() || !person.getFixedPhone().isEmpty() || !person.getEmail().isEmpty()
							|| !person.getWechat().isEmpty() || !person.getOtherContact().isEmpty())) {
				// 修改会议活动表中的嘉宾数据
				customer.setCustomerContact(personId);
				// 放在同一个事务中(新增专家，往中间表中插入数据，修改会议表中的嘉宾数据)
				customerService.addCustomerContact(customer, person);
				
				LuceneCustomer lucustomer = returnLuceCustomer(customer);
				IsolrOperation<LuceneCustomer> iso = new SolrOperation<>();
				iso.update("customer", lucustomer);
				
				//对象复制 person ==> lucenePerson
				//BeanUtils.copyProperties(person, lucenePerson);
				//创建isolrOperation接口对象指向其实现类 
				IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
				//把Person转换为LucenePerson
				LucenePerson lucenePerson = lucenePersonConversion(person);
				List<LucenePerson> list = new ArrayList<LucenePerson>();
				list.add(lucenePerson);
				isolrOperation.add("person", list);
				// System.out.println("专家入库成功！");
			} else {
				msg = "固定电话、手机、邮箱、微信、其他联系方式其中一个为空，请重新输入！";
				return addCustomerContact(customerPid, model, "", request);
			}

		} else {
			// 专家表中有对应的专家信息
			// 修改会议活动表中的嘉宾数据
			customer.setCustomerContact(queryPerson.getPid());
			customerService.update(customer);
			LuceneCustomer lucustomer = returnLuceCustomer(customer);
			IsolrOperation<LuceneCustomer> iso = new SolrOperation<>();
			iso.update("customer", lucustomer);
			
			// 转化为二进制保存
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
			if (person.getTalentLevel() != null) {
				person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
			}
			person.setPid(queryPerson.getPid());
			personService.update(person);
			
			/**
			 * 更新索引
			 */
			//创建isolrOperation接口对象指向其实现类 
			IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
			//把Person转换为LucenePerson
			LucenePerson lucenePerson = lucenePersonConversion(person);
			isolrOperation.update("person", lucenePerson);
			
		}
		// 将弹出窗错误信息传回前台
		model.addAttribute("msg", msg);
		return "redirect:/customer/customerList";
	}

	/**
	 * 修改客户联系人跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateCustomerContact")
	public String updateCustomerContact(@RequestParam("pid") String pid, Model model, HttpServletRequest request) {

		// 修改客户联系人，首先要把客户信息查询出来
		Customer customer = customerService.getById(pid);
		// 查询出联系人字段信息
		String contact = customer.getCustomerContact();

		if (StringUtil.isNotEmpty(contact)) {
			// 如果联系人id不为空，
			// 查出person信息
			Person person = personService.getById(contact);
			areaModel(model, person.getArea(), person.getDomesticOrForeign());
			return updateView(person.getPid(), model);
		} else {
			// 联系人id为空，跳至新增联系人页面
			return addCustomerContact(pid, model, "", request);
		}

	}

	/**
	 * 进入修改页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateView/{pid}", produces = "application/json;charset=UTF-8")
	public String updateView(@PathVariable("pid") String pid, Model model) {
		// 调用本类方法
		addListToModel(model);
		// 通过pid查询专家表
		Person person = personService.findPersonByPid(pid);

		// 回显三级联动
		String province = "";
		String cityId = "";
		String areaId = String.valueOf(person.getArea());
		if (areaId.length() < 10 && areaId.length() > 5) {
			// 说明是区的id,并截取得到省和市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("areaId", areaId);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}
		if (areaId.length() < 6 && areaId.length() > 2) {
			// 说明是市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}
		if (areaId.length() < 3 && areaId.length() > 0) {
			// 说明是省的id
			model.addAttribute("province", areaId);
		}

		// 所有市
		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
		// 所有区
		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

		// 所属领域二进制转化为字符串并存放到数组中
		String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
		// 人才级别二进制转化为字符串并存放到数组中
		String[] talentLevelFieldArr = null;
		if (person.getTalentLevel() != null) {
			talentLevelFieldArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
		}

		model.addAttribute("researchFieldArr", researchFieldArr);
		model.addAttribute("talentLevelFieldArr", talentLevelFieldArr);

		model.addAttribute("person", person);
		model.addAttribute("cityDictiontryList", cityDictiontryList);
		model.addAttribute("areaDictiontryList", areaDictiontryList);

		return "personUpdate";
	}

	/**
	 * 客户匹配需求，跳转项目列表页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/compareDemand")
	public String compareDemand(@RequestParam("pid") String pid, Model model,
			@RequestParam(defaultValue = "1") int pageNo) {

		// 将客户id传入
		model.addAttribute("customerId", pid);

		Demand demand = new Demand();
		demand.setArea("1111111111111111");
		pageInfo(model, pageNo, demand);
		addListToModel(model);

		return "customerconparedemand";
	}

	/**
	 * 客户匹配项目，跳转项目列表页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/compareProject")
	public String compareProject(@RequestParam("pid") String pid, Model model,
			@RequestParam(defaultValue = "1") int pageNo) {

		// 将客户id传入
		model.addAttribute("customerId", pid);

		Project project = new Project();
		pageInfo(model, pageNo, project);
		addListToModel(model);

		return "customerconpareproject";
	}

	/**
	 * 检索项目跳转控制器 xyx
	 * 
	 * @param model
	 * @param demand
	 * @param searchKeyword
	 * @param pageNo
	 * @return 2018年8月24日
	 */
	@RequestMapping("/showProjectConditionQuery")
	public String showProjectConditionQuery(@RequestParam("customerId") String customerId, Model model, Project project,
			String searchKeyword, @RequestParam(defaultValue = "1") int pageNo) {
		if (StringUtil.isEmpty(searchKeyword) && new Project().equals(project)) {// 判断是否为空对象，不要忘demand中的per属性中传值
			model.addAttribute("searchEmpty", "至少需要一个搜索条件");
			return compareProject(customerId, model, pageNo);
		}
		if (StringUtil.isNotEmpty(searchKeyword)) {
			if (searchKeyword.matches("R\\d{6,}"))
				project.setProjectNumber(Integer.parseInt(searchKeyword.replaceFirst("R", "")));
			else
				project.setProjectName(searchKeyword);
		}
		String[] researchFieldArr = null;
		String[] projectTypedArr = null;
		if (StringUtil.isNotEmpty(project.getProjectType())) {
			projectTypedArr = project.getProjectType().split(",");
			project.setProjectTypeNumber(projectTypedArr.length);
			project.setProjectTypeInteger(StrUtil.stringByByte(project.getProjectType()));
		}
		if (StringUtil.isNotEmpty(project.getResearchField())) {
			researchFieldArr = project.getResearchField().split(",");
			project.setResearchFieldNumber(researchFieldArr.length);
			project.setResearchFieldInteger(StrUtil.stringByByte(project.getResearchField()));
		}
		model.addAttribute("searchKeyword", searchKeyword);
		model.addAttribute("customerId", customerId);
		model.addAttribute("project", project);
		model.addAttribute("researchFieldArr", researchFieldArr);
		model.addAttribute("projectTypedArr", projectTypedArr);
		if (project.getArea() != null)
			areaModel(model, project.getArea(), project.getDomesticOrForeign());
		pageInfo(model, pageNo, project);
		return "customerconpareproject";
	}

	// public void pageInfo1(Model model, int pageNo, Demand dem) {
	// PageHelper.startPage(pageNo, DEFAULT_COUNT);
	// List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance()
	// .getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
	// List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance()
	// .getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);
	//
	// List<Demand> list = demandService.queryAll(dem);
	// list.forEach(
	// demand -> demand.setDemandType(getDictiontryWorth(demand.getDemandType(),
	// demandTypeDictiontryList)));
	// list.forEach(demand -> demand.setDemandStatusWorth(
	// demandStatusDictiontryList.stream().filter(dsd ->
	// dsd.getPid().equals(demand.getDemandStatus()))
	// .map(Dictiontry::getWorth).findAny().orElse("")));
	//
	// PageInfo<Demand> pageInfo = new PageInfo<Demand>(list);
	// addListToModel(model);
	// model.addAttribute(pageInfo);
	// }

	private void pageInfo(Model model, int pageNo, Project pro) {
		PageHelper.startPage(pageNo, 10);
		// 项目状态
		List<Dictiontry> projectStatusDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTSTATUS);
		// 项目类型
		List<Dictiontry> projectTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTTYPE);

		List<Project> list = projectService.queryAll(pro);
		list.forEach(project -> project
				.setProjectType(getDictiontryWorth(project.getProjectType(), projectTypeDictiontryList)));
		list.forEach(project -> project.setProjectStatusWorth(
				projectStatusDictiontryList.stream().filter(psd -> psd.getPid().equals(project.getProjectStatus()))
						.map(Dictiontry::getWorth).findAny().orElse("")));

		PageInfo<Project> pageInfo = new PageInfo<Project>(list);
		addListToModel(model);
		model.addAttribute(pageInfo);
	}

	/**
	 * 客户匹配需求，保存客户和需求的id xyx
	 * 
	 * @param pid
	 * @param model
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/saveCompareData", method = RequestMethod.GET)
	@ResponseBody
	public String saveCompareData(@RequestParam(value = "customerId", required = false) String customerId,
			@RequestParam(value = "checkStr", required = false) String checkStr, Model model,
			HttpServletRequest request) {

		// 获取登录人的uuid
		String userId = getUserInfoBySession(request).getUserId();

		// 获取客户信息
		Customer customer = customerService.getById(customerId);

		// 所有的需求id集合
		if (StringUtil.isNotEmpty(checkStr)) {
			String[] demandArray = checkStr.split(",");
			for (String demandId : demandArray) {
				if (StringUtil.isNotEmpty(demandId)) {
					Demand demand = demandService.getById(demandId);
					detailsService.addFirstButtDetails(null, demand, null, customer, null, userId);
				}
			}
		}
		return "success";
	}

	/**
	 * 客户匹配项目，保存客户和项目的id xyx
	 * 
	 * @param pid
	 * @param model
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/saveCompareProject", method = RequestMethod.GET)
	@ResponseBody
	public String saveCompareProject(@RequestParam(value = "customerId", required = false) String customerId,
			@RequestParam(value = "checkStr", required = false) String checkStr, Model model,
			HttpServletRequest request) {

		// 获取登录人的uuid
		String userId = getUserInfoBySession(request).getUserId();

		// 获取客户信息
		Customer customer = customerService.getById(customerId);

		// 所有的项目id集合
		if (StringUtil.isNotEmpty(checkStr)) {
			String[] projectArray = checkStr.split(",");
			for (String projectId : projectArray) {
				if (StringUtil.isNotEmpty(projectId)) {
					Project project = projectService.getById(projectId);
					detailsService.addFirstButtDetails(project, null, null, customer, null, userId);
				}
			}
		}
		return "success";
	}

	/**
	 * 查询匹配需求列表页 xyx
	 * 
	 * @param pageNum
	 * @param customerId
	 * @param request
	 * @return 2018年8月24日
	 */
	@RequestMapping(value = "/queryCustomerDemand")
	public String queryCustomerDemand(Integer pageNum, @RequestParam("pid") String customerId,
			HttpServletRequest request) {

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);

		// 根据当前会议id查询到中间表中关联的嘉宾信息
		List<ButtDetails> attrList = detailsService.findCustomerDemand(customerId);

		// 将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(attrList);

		for (int i = 0; i < attrList.size(); i++) {
			Demand demand = demandService.getById(attrList.get(i).getDemandNumber());
			if (demand != null) {
				attrList.get(i).setDemandName(demand.getDemandName());
				Customer customer = customerService.getById(customerId);
				attrList.get(i).setCustomerName(customer.getCustomerName());
			}
		}

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("pid", customerId);
		return "customerdemand";
	}

	@RequestMapping(value = "/queryCustomerProject")
	public String queryCustomerProject(Integer pageNum, @RequestParam("pid") String customerId,
			HttpServletRequest request) {

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);

		// 根据当前会议id查询到中间表中关联的嘉宾信息
		List<ButtDetails> attrList = detailsService.findCustomerProject(customerId);

		// 将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(attrList);

		for (int i = 0; i < attrList.size(); i++) {
			Project project = projectService.getById(attrList.get(i).getProjectNumber());
			if (project != null) {
				attrList.get(i).setProjectName(project.getProjectName());
				Customer customer = customerService.getById(customerId);
				attrList.get(i).setCustomerName(customer.getCustomerName());
			}
		}

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("pid", customerId);
		return "customerproject";
	}

	/**
	 * 转到项目匹配客户的页面
	 * 
	 * @author pdz
	 * @date 2018年8月29日
	 * @return
	 */
	@RequestMapping("/showProjectMatchedCustomer")
	public String showProjectMatchedCustomer(Model model, Project project) {
		PageInfo<Customer> pageInfo = new PageInfo<Customer>(new ArrayList<>());
		addListToModel(model);
		model.addAttribute(pageInfo);
		model.addAttribute("project", project);
		model.addAttribute("customer", new Customer());
		return "project/showProjectMatchedCustomer";
	}

	/**
	 * 搜索匹配的客户
	 * 
	 * @author pdz
	 * @date 2018年8月29日
	 * @param customer
	 * @param pageNum
	 * @param customerNumberId
	 * @param projectId
	 * @param project
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/searchMatchedCustomer")
	public String searchMatchedCustomer(Customer customer, @RequestParam(defaultValue = "1") Integer pageNum,
			String customerNumberId, String projectId, Project project, Model model, HttpServletRequest request) {
		project.setPid(projectId);
		if (StringUtil.isEmpty(customerNumberId) && StrUtil.isEmpty(customer)) {
			model.addAttribute("searchEmpty", "至少需要一个搜索条件");
			return showProjectMatchedCustomer(model, project);
		}
		model.addAttribute("project", project);
		customerList(customer, null, pageNum, model, customerNumberId,request);
		ButtDetails olderButt = new ButtDetails();
		// 根据projectid查询对接详情，然后筛选出已经对接过的demand
		olderButt.setProjectNumber(projectId);
		olderButt.setButtPersonId(getUserId(request));
		olderButt.setFuture(1);
		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
		PageInfo<Customer> pageInfo = (PageInfo<Customer>) model.asMap().get("pageInfo");
		List<String> searchCustomerIdList = pageInfo.getList().stream().map(Customer::getPid)
				.collect(Collectors.toList());
		// 取出搜索列表中已经对接的customerID
		List<String> buttedCustomerIdList = historyButtDetails.stream().map(ButtDetails::getCustomerNumber)
				.filter(StringUtil::isNotEmpty).filter(customerId -> searchCustomerIdList.contains(customerId))
				.collect(Collectors.toList());
		model.addAttribute("buttedCustomerIdList", buttedCustomerIdList);
		return "project/showProjectMatchedCustomer";
	}

	/**
	 * 项目匹配客户
	 * 
	 * @author pdz
	 * @date 2018年8月29日
	 * @param demandId
	 * @param demand
	 * @param projectId
	 * @param project
	 * @param request
	 * @return
	 */
	@RequestMapping("/projectMatchCustomer")
	@ResponseBody
	public String projectMatchCustomer(String customerId, Customer customer, String projectId, Project project,
			HttpServletRequest request) {
		customer.setPid(customerId);
		project.setPid(projectId);
		detailsService.addFirstButtDetails(project, null, null, customer, null, getUserId(request));
		return "success";
	}

	/**
	 * 查看客户参会情况
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryCustomerConference")
	public String queryCustomerConference(@RequestParam(value = "customerId") String customerId, Integer pageNum,
			Model model) {

		addListToModel(model);
		String cityId = "";
		String province = "";

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}

		// 查询所有会议活动数据
		List<ConfOfAttr> attrList = conOfAttrService.findAttrByCustomerId(customerId);
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		List<Conference> conList = new ArrayList<Conference>();

		// 遍历中间表中的会议id，查询出所有会议相关详细信息
		if (attrList != null && attrList.size() > 0) {
			for (ConfOfAttr ofattr : attrList) {
				// 取出会议id
				String conferenceId = ofattr.getConferenceId();
				Conference conference = conferenceService.getById(conferenceId);
				conList.add(conference);
			}
		}

		if (conList != null && conList.size() > 0) {
			for (int i = 0; i < conList.size(); i++) {
				String areaStr = "";
				String reachName = "";
				// 得到所属领域二进制
				String rearch = conList.get(i).getResearchField();
				// 得到areaId
				String areaIdStr = String.valueOf(conList.get(i).getArea());
				if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
					if (areaIdStr.length() == 4) {
						// 说明是国外的
						Dictiontry dicArea = new Dictiontry();
						dicArea.setPid(Integer.parseInt(areaIdStr));
						dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
						// 国外的名字
						areaStr=getAreaWorth(areaIdStr, 1);
						
					}

					if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
						// 说明是区的id
						// 截取得到省和市的id
						Dictiontry dicArea = new Dictiontry();
						dicArea.setNames(areaIdStr);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA);
						// 区的名字
						// areaStr =
						// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
						// + " ";
						//
						// cityId = areaIdStr.substring(0, 5);
						// dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
						// dicArea.setNames(cityId);
						// // 市的名字
						// areaStr +=
						// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
						// + " ";
						//
						// province = areaIdStr.substring(0, 2);
						// dicArea.setNames(province);
						// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
						// 省的名字
						areaStr = getAreaWorth(areaIdStr, 0);
					}

					if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
						// 说明是市的id
						Dictiontry dicArea = new Dictiontry();
						cityId = areaIdStr.substring(0, 5);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
						dicArea.setNames(cityId);
						// 市的名字
						// areaStr +=
						// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
						// + " ";
						//
						// province = areaIdStr.substring(0, 2);
						// dicArea.setNames(province);
						// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
						// // 省的名字
						// areaStr +=
						// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
						// + "";
						areaStr = getAreaWorth(areaIdStr, 0);
					}

					if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
						// 说明是省的id
						Dictiontry dicArea = new Dictiontry();
						province = areaIdStr.substring(0, 2);
						dicArea.setNames(province);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
						// 省的名字
						// areaStr +=
						// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
						// + "";
						areaStr = getAreaWorth(areaIdStr, 0);
					}
				}
				// 给地区附上名字
				conList.get(i).setAreaNameStr(areaStr);

				// 二进制转化为字符串
				reachName = getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
				// String rearchStr = StrUtil.byteToString(rearch);
				// String[] reaArray = rearchStr.split(",");
				// for (String reaStr : reaArray) {
				// Dictiontry dic = new Dictiontry();
				// dic.setGroupName(Constant.DICTIONTRY_PROJECTFIELD);
				// dic.setNames(reaStr);
				// List<Dictiontry> dicList =
				// dictiontryService.findDictiontryByNamesAndGroupName(dic);
				// for (Dictiontry dictiontry : dicList) {
				// reachName += dictiontry.getWorth() + " ";
				// }
				// }
				conList.get(i).setResearchFieldNameStr(reachName);
			}
		}

		// 将list放进PageInfo
		PageInfo<Conference> pageInfo = new PageInfo<Conference>(conList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);
		return "customerqueryconferencelist";
	}

	/**
	 * 客户匹配需求详情
	 * 
	 * @date 2018年8月22日
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "findButtDetailsList", produces = "application/json;charset=UTF-8")
	public String findButtDetailsList(String pid, Integer pageNo, HttpServletRequest request, ButtDetails buttDetails) {
		// 分页
		if (null == pageNo) {
			pageNo = 1;
		}
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);

		// 将专家的pid封装到对接详情中
		buttDetails.setCustomerNumber(pid);

		buttDetails.setButtPersonId(getUserId(request));
		buttDetails.setFuture(1);
		buttDetails.setDemandNumberEmpty(false);

		// 从缓存中获取对接状态
		List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
		// 将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(list);

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("buttStatus", buttStatus);

		return "customerDemandDetails";
	}

	/**
	 * 客户匹配项目详情
	 * 
	 * @date 2018年8月22日
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "findButtProjectList", produces = "application/json;charset=UTF-8")
	public String findButtProjectList(String pid, Integer pageNo, HttpServletRequest request, ButtDetails buttDetails) {
		// 分页
		if (null == pageNo) {
			pageNo = 1;
		}
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);

		// 将专家的pid封装到对接详情中
		buttDetails.setCustomerNumber(pid);

		buttDetails.setButtPersonId(getUserId(request));
		buttDetails.setFuture(1);
		buttDetails.setProjectNumberEmpty(false);

		// 从缓存中获取对接状态
		List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
		// 将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(list);

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("buttStatus", buttStatus);

		return "customerProjectbutton";
	}

	@ResponseBody
	@RequestMapping(value = "/ajaxmateProjectView", produces = "application/json;charset=UTF-8")
	public List ajaxmateProjectView(HttpServletRequest request, @RequestParam("pid") String pid) {

		ButtDetails buttDetails = new ButtDetails();
		// 将专家的pid封装到对接详情中
		buttDetails.setCustomerNumber(pid);

//		buttDetails.setButtPersonId(getUserId(request));
		buttDetails.setFuture(1);
		buttDetails.setProjectNumberEmpty(false);

		// 从缓存中获取对接状态
		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
		list.forEach(bd -> bd.setRemark2(bd.getCustomerName() + "<br>" + bd.getProjectName()));
		
		for (int i = 0; i < list.size(); i++) {
			
			String projectId=list.get(i).getProjectNumber();
			Project project=projectService.getById(projectId);
			list.get(i).setProjectName(project.getProjectName());
			list.get(i).setProjectNum("R"+project.getProjectNumber());
			list.get(i).setProjectType(getDicCheckboxWorth(project.getProjectType(), Constant.DICTIONTRY_PROJECTTYPE));
			list.get(i).setButtStatusStr(getDicSingleWorth(project.getProjectStatus(), Constant.DICTIONTRY_PROJECTSTATUS));
			String personName="";
			if(StringUtil.isNotEmpty(project.getProjectContactId())){
				personName=personService.findPersonByPid(project.getProjectContactId()).getName();
			}
			list.get(i).setButtName(personName);
			
		}
		return list;
	}

	/**
	 * 查看客户匹配的历史详情
	 * 
	 * @date 2018年8月29日
	 * @param pageNo
	 * @param buttdetails
	 * @param request
	 * @return
	 */
	@RequestMapping("/findHistoryButtDetails")
	public String findHistoryButtDetails(Integer pageNo, String pid, HttpServletRequest request) {
		try {
			// 从缓冲中获取对接状态
			List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
			request.setAttribute("buttStatus", buttStatus);
			// 通过对接详情pid查询对接详情
			ButtDetails buttd = detailsService.findDetailsByPid(pid);
			// 分页
			if (null == pageNo) {
				pageNo = 1;
			}
			PageHelper.startPage(pageNo, DEFAULT_COUNT);
			// 将future设置为0，表示过期数据
			buttd.setFuture(0);
			// 通过外键查询对接详情
			List<ButtDetails> listbutt = detailsService.findHistoryButtDetails(buttd);

			PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(listbutt);
			request.setAttribute("pageInfo", pageInfo);
			request.setAttribute("pageInfo", pageInfo);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "customerdemandhistorydetails";
	}

	/**
	 * 客户匹配项目详情
	 * 
	 * @date 2018年8月22日
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/queryCustomerProject", produces = "application/json;charset=UTF-8")
	public String queryCustomerProject(String pid, Integer pageNo, HttpServletRequest request,
			ButtDetails buttDetails) {
		// 分页
		if (null == pageNo) {
			pageNo = 1;
		}
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);

		// 将专家的pid封装到对接详情中
		buttDetails.setCustomerNumber(pid);

		// 从缓存中获取对接状态
		List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		// 通过专家模糊查询对接详情
		List<ButtDetails> list = detailsService.findProjectByCustomerId(buttDetails);
		// 将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(list);

		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("buttStatus", buttStatus);

		return "customerProjectDetails";
	}

	@RequestMapping(value = "pipei")
	@ResponseBody
	public String pipei(String demandId, Demand demand, String customerId, Customer customer,
			HttpServletRequest request) {
		demand.setPid(demandId);
		customer.setPid(customerId);
		detailsService.addFirstButtDetails(null, demand, null, customer, null, getUserId(request));
		return "success";
	}

	/**
	 * 进入专家匹配需求页面
	 * 
	 * @date 2018年8月27日
	 * @param pid
	 * @param model
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "mateDemandView")
	public String mateDemandView(Customer customer, Model model) {

		PageInfo<Demand> pageInfo = new PageInfo<Demand>(new ArrayList<>());
		addListToModel(model);
		model.addAttribute(pageInfo);
		model.addAttribute("customer", customer);

		return "customerOfDemandList";
	}

	@ResponseBody
	@RequestMapping(value = "/ajaxmateDemandView", produces = "application/json;charset=UTF-8")
	public List ajaxmateDemandView(HttpServletRequest request, @RequestParam("pid") String pid) {

		//通过客户Number，查询关联的需求
		Customer customer=customerService.getById(pid);
		Demand demand=new Demand();
		demand.setSourceRemark("C"+customer.getCustomerNumber());
		List<Demand> demandList=demandService.queryAll(demand);
		
		List<ButtDetails> allDemandList=new ArrayList<ButtDetails>();
		
		//查看当前需求是否被匹配
		for (Demand dem : demandList) {
			ButtDetails buttDetails = new ButtDetails();
			buttDetails.setDemandNumber(dem.getPid());
			buttDetails.setButtPersonId(getUserId(request));
			List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
			list=removeDuplicateUser(list);
			//所有已经匹配的需求 
			if(list!=null && list.size()>0){
				allDemandList.addAll(list);
			}
		}
		
		
		//查看当前未被匹配的需求
//		for (Demand dem : demandList) {
//			ButtDetails buttDetails = new ButtDetails();
//			buttDetails.setDemandNumber(dem.getPid());
//		    buttDetails.setButtPersonId(getUserId(request));
//			List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
//			list=removeDuplicateUser(list);
//			//所有未被匹配的需求 
//			if(list==null && list.size()==0){
//				allDemandList.addAll(list);
//			}
//		}
		
		List<Demand> hasbeenCompareList=new ArrayList<Demand>();
		//将需求List返回至页面
		for (ButtDetails buttDetails : allDemandList) {
			//得到需求id
			String demandId=buttDetails.getDemandNumber();
			Demand allDem=demandService.getById(demandId);
			hasbeenCompareList.add(allDem);
		}
		
		for (int i = 0; i < hasbeenCompareList.size(); i++) {
            if(StringUtil.isNotEmpty(hasbeenCompareList.get(i).getDemandContactId())){
            	hasbeenCompareList.get(i).setDemandContactName(personService.getById(hasbeenCompareList.get(i).getDemandContactId()).getName());
			}
		}
		hasbeenCompareList.forEach(dem -> dem.setDemandType(getDicCheckboxWorth(dem.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE)));
		hasbeenCompareList.forEach(dem -> dem.setDemandNumberStr("D"+dem.getDemandNumber()));
		hasbeenCompareList.forEach(dem -> dem.setCustomerId(customer.getPid()));
		hasbeenCompareList.forEach(dem -> dem.setDemandStatusWorth(getDicSingleWorth(dem.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS)));
		
		
		/*ButtDetails buttDetails = new ButtDetails();
		// 将专家的pid封装到对接详情中
		buttDetails.setCustomerNumber(pid);

		buttDetails.setButtPersonId(getUserId(request));
		buttDetails.setFuture(1);
		buttDetails.setDemandNumberEmpty(false);

		// 从缓存中获取对接状态
		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
		list.forEach(bd -> bd.setRemark2(bd.getCustomerName() + "<br>" + bd.getDemandName()));
		for (int i = 0; i < list.size(); i++) {
			// 取出对接状态
			int statues = list.get(i).getButtStatus();
			if (statues == 1) {
				list.get(i).setButtStatusStr("沟通对接需求");
			} else if (statues == 2) {
				list.get(i).setButtStatusStr("已签合作协议");
			} else if (statues == 3) {
				list.get(i).setButtStatusStr("执行对接任务");
			} else if (statues == 4) {
				list.get(i).setButtStatusStr("完成对接需求");
			}
		}*/
		return hasbeenCompareList;
	}

	/**
	 * 进入专家匹配项目页面
	 * 
	 * @date 2018年8月27日
	 * @param pid
	 * @param model
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "/mateProjectView")
	public String mateProjectView(Customer customer, Model model,HttpServletRequest request) {

		PageHelper.startPage(1, DEFAULT_COUNT);
		List<Project> list = projectService.queryAll(new Project());
        PageInfo<Project> pageInfo = new PageInfo<Project>(list);
        pageInfo.getList().forEach(project -> project.setProjectType(getDicCheckboxWorth(project.getProjectType(), Constant.DICTIONTRY_PROJECTTYPE)));
        pageInfo.getList().forEach(project -> project.setProjectStatusWorth(getDicSingleWorth(project.getProjectStatus(), Constant.DICTIONTRY_PROJECTSTATUS)));
	        
        ButtDetails buttDetails = new ButtDetails();
        buttDetails.setButtPersonId(getUserId(request));
        buttDetails.setCustomerNumber(customer.getPid());
        buttDetails.setFuture(1);
        buttDetails.setProjectNumberEmpty(false);
        List<ButtDetails> detailList = detailsService.findButtDetails(buttDetails);
        List<String> buttedProjectIdList = detailList.stream().map(ButtDetails::getProjectNumber).distinct().collect(Collectors.toList());
        
		model.addAttribute("customer", customer);
        model.addAttribute(pageInfo);
        
        addListToModel(model);
		
//		searchMatchedProject(model, null, null, null, null, 1, request, customer.getPid());

        model.addAttribute("buttedProjectIdList", buttedProjectIdList);
		return "customerOfProjectList";
	}

	@RequestMapping("/searchMatchedProject")
	public String searchMatchedProject(Model model, Project project, String searchKeyword,
			@RequestParam(defaultValue = "1") int pageNo, String customerId, Customer customer,
			HttpServletRequest request) {
		customer.setPid(customerId);

		if (StrUtil.isEmpty(project) && StringUtil.isEmpty(searchKeyword)) {
			return mateProjectView(customer, model,request);
		}
		model.addAttribute("customer", customer);
		PageInfo<Project> searchPageInfo = searchPageInfo(model, project, searchKeyword, pageNo);
		// 根据customerId查询对接详情，然后筛选出已经对接过的demand
		ButtDetails olderButt = new ButtDetails();
		olderButt.setCustomerNumber(customerId);
		olderButt.setButtPersonId(getUserId(request));
		olderButt.setFuture(1);
		List<String> searchDemandIdList = searchPageInfo.getList().stream().map(Project::getPid)
				.collect(Collectors.toList());
		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
		List<String> buttedProjectIdList = historyButtDetails.stream().map(ButtDetails::getProjectNumber)
				.filter(StringUtil::isNotEmpty).filter(projectId -> searchDemandIdList.contains(projectId))
				.collect(Collectors.toList());
		model.addAttribute("buttedProjectIdList", buttedProjectIdList);
		return "customerOfProjectList";
	}


	private PageInfo<Demand> pageInfo(Model model, int pageNo, Demand dem) {
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
		List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);

		List<Demand> list = demandService.queryAll(dem);
		list.forEach(
				demand -> demand.setDemandType(getDictiontryWorth(demand.getDemandType(), demandTypeDictiontryList)));
		list.forEach(demand -> demand.setDemandStatusWorth(
				demandStatusDictiontryList.stream().filter(dsd -> dsd.getPid().equals(demand.getDemandStatus()))
						.map(Dictiontry::getWorth).findAny().orElse("")));

		PageInfo<Demand> pageInfo = new PageInfo<Demand>(list);
		addListToModel(model);
		model.addAttribute(pageInfo);
		return pageInfo;
	}

	/**
	 * 搜索客户匹配的需求
	 * 
	 * @date 2018年8月28日
	 * @param model
	 * @param demand
	 *            用于搜索
	 * @param searchKeyword
	 *            用于搜索
	 * @param pageNo
	 * @param projectId
	 * @param project
	 * @return
	 */
//	@RequestMapping("/searchMatchedDemand")
//	public String searchMatchedDemand(Model model, Demand demand, String searchKeyword,
//			@RequestParam(defaultValue = "1") int pageNo, String customerId, Customer customer,
//			HttpServletRequest request) {
//		customer.setPid(customerId);
//
//		if (StrUtil.isEmpty(demand) && StringUtil.isEmpty(searchKeyword)) {
//			return mateDemandView(customer, model);
//		}
//
//		model.addAttribute("customer", customer);
//		PageInfo<Demand> searchPageInfo = searchPageInfo(model, demand, searchKeyword, pageNo);
//		// 根据customerId查询对接详情，然后筛选出已经对接过的demand
//		ButtDetails olderButt = new ButtDetails();
//		olderButt.setCustomerNumber(customerId);
//		olderButt.setButtPersonId(getUserId(request));
//		olderButt.setFuture(1);
//		List<String> searchDemandIdList = searchPageInfo.getList().stream().map(Demand::getPid)
//				.collect(Collectors.toList());
//		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
//		List<String> buttedDemandIdList = historyButtDetails.stream().map(ButtDetails::getDemandNumber)
//				.filter(StringUtil::isNotEmpty).filter(demandId -> searchDemandIdList.contains(demandId))
//				.collect(Collectors.toList());
//		model.addAttribute("buttedDemandIdList", buttedDemandIdList);
//		return "customerOfDemandList";
//	}

//	/**
//	 * 搜索客户项目的需求
//	 * 
//	 * @date 2018年8月28日
//	 * @param model
//	 * @param demand
//	 *            用于搜索
//	 * @param searchKeyword
//	 *            用于搜索
//	 * @param pageNo
//	 * @param projectId
//	 * @param project
//	 * @return
//	 */
//	@RequestMapping("/searchMatchedProject")
//	public String searchMatchedProject(Model model, Project project, String searchKeyword,
//			@RequestParam(defaultValue = "1") int pageNo, String customerId, Customer customer,
//			HttpServletRequest request) {
//		customer.setPid(customerId);
//
//		model.addAttribute("customer", customer);
//		PageInfo<Project> searchPageInfo = searchPageInfo(model, project, searchKeyword, pageNo);
//		// 根据customerId查询对接详情，然后筛选出已经对接过的demand
//		ButtDetails olderButt = new ButtDetails();
//		olderButt.setCustomerNumber(customerId);
//		olderButt.setButtPersonId(getUserId(request));
//		olderButt.setFuture(1);
//		List<String> searchDemandIdList = searchPageInfo.getList().stream().map(Project::getPid)
//				.collect(Collectors.toList());
//		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
//		List<String> buttedProjectIdList = historyButtDetails.stream().map(ButtDetails::getProjectNumber)
//				.filter(StringUtil::isNotEmpty).filter(projectId -> searchDemandIdList.contains(projectId))
//				.collect(Collectors.toList());
//		model.addAttribute("buttedProjectIdList", buttedProjectIdList);
//		return "customerOfProjectList";
//	}

	/**
	 * 根据搜索条件查询分页
	 * 
	 * @author pdz
	 * @date 2018年8月29日
	 * @param model
	 * @param project
	 * @param searchKeyword
	 * @param pageNo
	 * @return
	 */
	private PageInfo<Project> searchPageInfo(Model model, Project project, String searchKeyword, int pageNo) {
		if (StringUtil.isEmpty(searchKeyword) && new Project().equals(project)) {// 判断是否为空对象，不要忘demand中的per属性中传值
			return pageProjectInfo(model, pageNo, project);
		}
		if (StringUtil.isNotEmpty(searchKeyword)) {
			if (searchKeyword.matches("R\\d{6,}"))
				project.setProjectNumber(Integer.parseInt(searchKeyword.replaceFirst("R", "")));
			else
				project.setProjectName(searchKeyword);
		}
		String[] researchFieldArr = null;
		String[] projectTypedArr = null;
		if (StringUtil.isNotEmpty(project.getProjectType())) {
			projectTypedArr = project.getProjectType().split(",");
			project.setProjectTypeNumber(projectTypedArr.length);
			project.setProjectTypeInteger(StrUtil.stringByByte(project.getProjectType()));
		}
		if (StringUtil.isNotEmpty(project.getResearchField())) {
			researchFieldArr = project.getResearchField().split(",");
			project.setResearchFieldNumber(researchFieldArr.length);
			project.setResearchFieldInteger(StrUtil.stringByByte(project.getResearchField()));
		}
		model.addAttribute("searchKeyword", searchKeyword);
		model.addAttribute("project", project);
		model.addAttribute("researchFieldArr", researchFieldArr);
		model.addAttribute("projectTypedArr", projectTypedArr);
		if (project.getArea() != null)
			areaModel(model, project.getArea(), project.getDomesticOrForeign());
		PageInfo<Project> pageInfo = pageProjectInfo(model, pageNo, project);
		return pageInfo;
	}

	/**
	 * 查询分页
	 * 
	 * @author pdz
	 * @date 2018年8月29日
	 * @param model
	 * @param pageNo
	 * @param pro
	 * @return
	 */
	private PageInfo<Project> pageProjectInfo(Model model, int pageNo, Project pro) {
		PageHelper.startPage(pageNo, 10);
		// 项目状态
		List<Dictiontry> projectStatusDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTSTATUS);
		// 项目类型
		List<Dictiontry> projectTypeDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTTYPE);

		List<Project> list = projectService.queryAll(pro);
		list.forEach(project -> project
				.setProjectType(getDictiontryWorth(project.getProjectType(), projectTypeDictiontryList)));
		list.forEach(project -> project.setProjectStatusWorth(
				projectStatusDictiontryList.stream().filter(psd -> psd.getPid().equals(project.getProjectStatus()))
						.map(Dictiontry::getWorth).findAny().orElse("")));

		PageInfo<Project> pageInfo = new PageInfo<Project>(list);
		addListToModel(model);
		model.addAttribute(pageInfo);
		return pageInfo;
	}

	@RequestMapping("/pipeiProject")
	@ResponseBody
	public String pipeiProject(String projectId, Project project, String customerId, Customer customer,
			HttpServletRequest request) {
		project.setPid(projectId);
		customer.setPid(customerId);
		detailsService.addFirstButtDetails(project, null, null, customer, null, getUserId(request));
		return "successTuiSong";
	}

	// 提取添加页面回显的公共方法
	public void addInfo(Person person, Model model) {
		// 获取地区相关数据，便于回显
		String areaId = person.getArea();
		String cityId = "";
		String province = "";
		if (StringUtil.isNotEmpty(areaId)) {
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
				// 说明是区的id
				// 截取得到省和市的id
				cityId = areaId.substring(0, 5);
				province = areaId.substring(0, 2);
				model.addAttribute("areaId", areaId);
				model.addAttribute("cityId", cityId);
				model.addAttribute("province", province);
			}
			if (areaId.length() < 3 && areaId.length() > 0) {
				// 说明是省的id
				model.addAttribute("province", areaId);
			}
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
				// 说明是市的id
				// 截取得到省和市的id
				cityId = areaId;
				province = areaId.substring(0, 2);
				model.addAttribute("province", province);
				model.addAttribute("cityId", cityId);
			}

			// 所有市
			List<Dictiontry> cityDictiontryList = getCityByProvince(province);
			// 所有区
			List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

			model.addAttribute("cityDictiontryList", cityDictiontryList);
			model.addAttribute("areaDictiontryList", areaDictiontryList);
		}

		// 回显所属领域
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
		}
		if (researchFieldArr != null) {
			model.addAttribute("researchFieldArr", researchFieldArr);
		} else {
			model.addAttribute("researchFieldArr", "");
		}
		// 回显人才级别
		String[] talentLevelArr = null;
		if (StringUtil.isNotEmpty(person.getTalentLevel())) {
			talentLevelArr = person.getTalentLevel().split(",");
		}
		if (talentLevelArr != null) {
			model.addAttribute("talentLevelArr", talentLevelArr);
		} else {
			model.addAttribute("talentLevelArr", "");
		}

		if (person.getDomesticOrForeign() != null) {
			if (person.getDomesticOrForeign() == 1) {
				model.addAttribute("countryId", Integer.parseInt(areaId));
			}
		}

	}

	/***
	 * @date 2018-08-23
	 * @author dq
	 * @param detailPid
	 *            对接详情的PId 显示添加对接详情页面
	 * @return
	 */
	@RequestMapping(value = "/showAddButtDetails")
	public String showAddButtDetails(String detailPid, Model model,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "customerId", required = false) String customerId) {
		List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		ButtDetails buttDeteils = new ButtDetails();
		model.addAttribute("buttDeteils", buttDeteils);
		model.addAttribute("detailPid", detailPid);
		model.addAttribute("buttStatus", buttStatus);

		model.addAttribute("origType", origType);
		model.addAttribute("customerPid", customerId);

		ButtDetails de = detailsService.findDetailsByPid(detailPid);
		model.addAttribute("details", de.getButtDetails());
		model.addAttribute("buttDe", de);
		if (null != de) {
			if (de.getProjectNumber() != null && !"".equals(de.getProjectNumber())) {
				Project project = projectService.getById(de.getProjectNumber());
				model.addAttribute("project", project);

			}
			if (de.getDemandNumber() != null && !"".equals(de.getDemandNumber())) {

				Demand demand = demandService.getById(de.getDemandNumber());
				model.addAttribute("demand", demand);
			}
			if (de.getExpertNumber() != null && !"".equals(de.getExpertNumber())) {
				Person person = personService.getById(de.getExpertNumber());
				model.addAttribute("person", person);

			}
			if (de.getCustomerNumber() != null && !"".equals(de.getCustomerNumber())) {
				Customer customer = customerService.getById(de.getCustomerNumber());
				model.addAttribute("customer", customer);

			}
			if (de.getConferenceNumber() != null && !"".equals(de.getConferenceNumber())) {
				Conference conference = conferenceService.getById(de.getConferenceNumber());
				model.addAttribute("conference", conference);
			}

		}
		return "customeraddprojectdetails";
	}

	/***
	 * @date 2018-08-23
	 * @author dq 添加对接详情页面
	 * @return
	 */
	@RequestMapping(value = "/addButtDetails", method = RequestMethod.POST)
	public String addButtDetails(@Valid ButtDetails buttDetails, BindingResult bindingResult, String detailPid,
			MultipartFile buttDetailsFiles, Model model, HttpServletRequest request,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "customerPid", required = false) String customerPid) {

		ButtDetails oldButt = null;

		try {
			oldButt = detailsService.findDetailsByPid(detailPid);

			buttDetails.setFuture(1);
			buttDetails.setAddDateTime(StrUtil.getCurrentDateTime_two());
			buttDetails.setButtPersonId(this.getUserId(request));
			buttDetails.setButtName(this.getUserInfoBySession(request).getFullName());
			if (null != buttDetailsFiles && !buttDetailsFiles.isEmpty()) {
				// 文件名字
				String fileName = buttDetailsFiles.getOriginalFilename();
				String oldFileName = FileUtils.generateFileName("buttdetails", fileName);

				buttDetails.setButtaNnex(oldFileName);
				try {
					FileUtils.uploadFile(buttDetailsFiles.getBytes(), Constant.DEF_BUT_DETAILS_PATH, oldFileName);
				} catch (Exception e) {
					logger.error("上传文件失败：" + e.getMessage());
				}
			}
			detailsService.addButtDetails(oldButt, buttDetails);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (StringUtil.isNotEmpty(origType)) {
			return "redirect:/customer/showDetail?customerId=" + customerPid;
		}
		return findButtProjectList(oldButt.getCustomerNumber(), null, request, new ButtDetails());
	}

	/***
	 * @date 2018-08-23
	 * @author dq
	 * @param detailPid
	 *            对接详情的PId 显示添加对接详情页面
	 * @return
	 */
	@RequestMapping(value = "/showAddDemandDetails")
	public String showAddDemandDetails(String detailPid, Model model,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "customerId", required = false) String customerId) {
		List<Dictiontry> buttStatus = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		ButtDetails buttDeteils = new ButtDetails();
		model.addAttribute("buttDeteils", buttDeteils);
		model.addAttribute("detailPid", detailPid);
		model.addAttribute("buttStatus", buttStatus);

		model.addAttribute("origType", origType);
		model.addAttribute("customerPid", customerId);

		ButtDetails de = detailsService.findDetailsByPid(detailPid);
		model.addAttribute("details", de.getButtDetails());
		model.addAttribute("buttDe", de);
		if (null != de) {
			if (de.getProjectNumber() != null && !"".equals(de.getProjectNumber())) {
				Project project = projectService.getById(de.getProjectNumber());
				model.addAttribute("project", project);

			}
			if (de.getDemandNumber() != null && !"".equals(de.getDemandNumber())) {

				Demand demand = demandService.getById(de.getDemandNumber());
				model.addAttribute("demand", demand);
			}
			if (de.getExpertNumber() != null && !"".equals(de.getExpertNumber())) {
				Person person = personService.getById(de.getExpertNumber());
				model.addAttribute("person", person);

			}
			if (de.getCustomerNumber() != null && !"".equals(de.getCustomerNumber())) {
				Customer customer = customerService.getById(de.getCustomerNumber());
				model.addAttribute("customer", customer);

			}
			if (de.getConferenceNumber() != null && !"".equals(de.getConferenceNumber())) {
				Conference conference = conferenceService.getById(de.getConferenceNumber());
				model.addAttribute("conference", conference);
			}

		}
		return "customeradddemanddetails";
	}

	@RequestMapping(value = "/addDemandDetails", method = RequestMethod.POST)
	public String addDemandDetails(@Valid ButtDetails buttDetails, BindingResult bindingResult, String detailPid,
			MultipartFile buttDetailsFiles, Model model, HttpServletRequest request,
			@RequestParam(value = "origType", required = false) String origType,
			@RequestParam(value = "customerPid", required = false) String customerPid) {

		ButtDetails oldButt = null;

		try {
			oldButt = detailsService.findDetailsByPid(detailPid);

			buttDetails.setFuture(1);
			buttDetails.setAddDateTime(StrUtil.getCurrentDateTime_two());
			buttDetails.setButtPersonId(this.getUserId(request));
			buttDetails.setButtName(this.getUserInfoBySession(request).getFullName());
			if (null != buttDetailsFiles && !buttDetailsFiles.isEmpty()) {
				// 文件名字
				String fileName = buttDetailsFiles.getOriginalFilename();
				String oldFileName = FileUtils.generateFileName("buttdetails", fileName);

				buttDetails.setButtaNnex(oldFileName);
				try {
					FileUtils.uploadFile(buttDetailsFiles.getBytes(), Constant.DEF_BUT_DETAILS_PATH, oldFileName);
				} catch (Exception e) {
					logger.error("上传文件失败：" + e.getMessage());
				}
			}
			detailsService.addButtDetails(oldButt, buttDetails);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (StringUtil.isNotEmpty(origType)) {
			return "redirect:/customer/showDetail?customerId=" + customerPid;
		}
		return findButtDetailsList(oldButt.getCustomerNumber(), null, request, new ButtDetails());
	}

	@RequestMapping("/showDetail")
	public String showDetail(String customerId, Model model,Integer lookExpert, String expertId, String lookPwd,HttpServletRequest request) {
		Customer customer = customerService.getById(customerId);
		//通过pid查询用户
		User user = userService.findUserById(customer.getCollectPersonId());
		// 获取联系人Id
		String personId = customer.getCustomerContact();
		if (StringUtil.isNotEmpty(personId)) {
			// 通过pid查询专家表
			Person person = personService.findPersonByPid(personId);
			if (person != null) {
				person.setSourceWorth(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
				person.setTypeWorth(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
				person.setResearchField(
						getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
				if (person.getTalentLevel() != null) {
					person.setTalentLevel(
							getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
				}
				person.setAreaWorth(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
//				if(StringUtil.isNotEmpty(person.getTell()) && person.getTell().length()>=11){
//					person.setTell(person.getTell().substring(0, 3) + "****" + person.getTell().substring(7, person.getTell().length()));
//				}
//				if(StringUtil.isNotEmpty(person.getFixedPhone()) && person.getFixedPhone().length()>=8){
//					person.setFixedPhone(person.getFixedPhone().substring(0, 3) + "****" + person.getFixedPhone().substring(7, person.getFixedPhone().length()));
//				}
//				if(StringUtil.isNotEmpty(person.getEmail()) && person.getEmail().length()>=5){
//					person.setEmail("****"+person.getEmail().substring(5, person.getEmail().length()));
//				}
//				if(StringUtil.isNotEmpty(person.getWechat()) && person.getWechat().length()>=3){
//					person.setWechat("***"+person.getWechat().substring(3, person.getWechat().length()));
//				}
//				if(StringUtil.isNotEmpty(person.getOtherContact()) && person.getOtherContact().length()>=3){
//					person.setOtherContact("***"+person.getOtherContact().substring(3, person.getOtherContact().length()));
//				}
			}
			model.addAttribute("person", person);
		}
		customer.setResearchFieldNameStr(
				getDicCheckboxWorth(customer.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
		customer.setAreaNameStr(getAreaWorth(customer.getArea(), customer.getDomesticOrForeign()));

		customer.setCustomerSourceName(
				getDicSingleWorth(customer.getCustomerSource(), Constant.DICTIONTRY_CUSTOMERSOURCE));
		customer.setCustomerTypeName(getDicSingleWorth(customer.getCustomerType(), Constant.DICTIONTRY_CUSTOMERTYPE));
		customer.setCustomerNatureName(
				getDicSingleWorth(customer.getCustomerNature(), Constant.DICTIONTRY_CUSTOMERNATURE));

		customer.setCurrentStateName(getDicSingleWorth(customer.getCurrentState(), Constant.DICTIONTRY_CURRENTSATUS));
		customer.setIntentionCooperate2Name(
				getDicSingleWorth(customer.getIntentionCooperate2(), Constant.DICTIONTRY_INTENTIONCOOPERATE2));
		customer.setIntentionCooperateName(
				getDicSingleWorth(customer.getIntentionCooperate(), Constant.DICTIONTRY_INTENTIONCOOPERATE));
		model.addAttribute("customer", customer);
		model.addAttribute("user",user);
		 //lookExpert为1表示要查看联系方式
        if (lookExpert != null && lookExpert.equals(1)) 
        	checkLookExpert(expertId, lookPwd, request);
		return "showCustomerDetail";
	}

	@ResponseBody
	@RequestMapping(value = "/ajaxCustomerContact", produces = "application/json;charset=UTF-8")
	public List ajaxCustomerContact(HttpServletRequest request, @RequestParam("pid") String pid) {
		List<Person> personList = new ArrayList<Person>();
		Customer customer = customerService.getById(pid);
		// 获取联系人Id
		String personId = customer.getCustomerContact();
		if (StringUtil.isNotEmpty(personId)) {
			// 通过pid查询专家表
			Person person = personService.findPersonByPid(personId);
			if (person != null) {
				person.setSourceWorth(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
				person.setTypeWorth(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
				person.setResearchField(
						getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
				if (person.getTalentLevel() != null) {
					person.setTalentLevel(
							getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
				}
				person.setAreaWorth(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
			}
			personList.add(person);
		}
		return personList;
	}

	@SuppressWarnings("null")
	@ResponseBody
	@RequestMapping(value = "/ajaxnotCompareDemand", produces = "application/json;charset=UTF-8")
	public List ajaxnotCompareDemand(HttpServletRequest request, @RequestParam("pid") String pid) {

		/*SolrOperation<Customer> slp = new SolrOperation<>();
		Pagination pagination = slp.queryList(1, 10, 2, pid);
		List<LuceneDemand> list = pagination.getList();

		List<ButtDetails> demandButtDetailList = ajaxmateDemandView(request, pid);
		// 将已经匹配的demandId设为null，在页面判断
		list.stream().filter(lp -> demandButtDetailList.stream().map(ButtDetails::getDemandNumber)
				.anyMatch(proId -> proId.equals(lp.getDemandId()))).forEach(lp -> lp.setDemandId(null));*/
		
		//通过客户Number，查询关联的需求
		Customer customer=customerService.getById(pid);
		Demand demand=new Demand();
		demand.setSourceRemark("C"+customer.getCustomerNumber());
		List<Demand> demandList=demandService.queryAll(demand);
		
		List<ButtDetails> allDemandList=new ArrayList<ButtDetails>();
		
		//查看当前未被匹配的需求
		for (Demand dem : demandList) {
			ButtDetails buttDetails = new ButtDetails();
			buttDetails.setDemandNumber(dem.getPid());
		    buttDetails.setButtPersonId(getUserId(request));
			List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
			list=removeDuplicateUser(list);
			//所有未被匹配的需求 
			if(list.size()==0){
				allDemandList.add(buttDetails);
			}
		}
		
		List<Demand> hasbeenCompareList=new ArrayList<Demand>();
		//将需求List返回至页面
		for (ButtDetails buttDetails : allDemandList) {
			//得到需求id
			String demandId=buttDetails.getDemandNumber();
			Demand allDem=demandService.getById(demandId);
			hasbeenCompareList.add(allDem);
		}
		
		for (int i = 0; i < hasbeenCompareList.size(); i++) {
            if(StringUtil.isNotEmpty(hasbeenCompareList.get(i).getDemandContactId())){
            	hasbeenCompareList.get(i).setDemandContactName(personService.getById(hasbeenCompareList.get(i).getDemandContactId()).getName());
			}
		}
		hasbeenCompareList.forEach(dem -> dem.setDemandType(getDicCheckboxWorth(dem.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE)));
		hasbeenCompareList.forEach(dem -> dem.setDemandNumberStr("D"+dem.getDemandNumber()));
		hasbeenCompareList.forEach(dem -> dem.setCustomerId(customer.getPid()));
		hasbeenCompareList.forEach(dem -> dem.setDemandStatusWorth(getDicSingleWorth(dem.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS)));
		
		
		return hasbeenCompareList;

	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/ajaxnotCompareProject", produces = "application/json;charset=UTF-8")
	public List ajaxnotCompareProject(HttpServletRequest request, @RequestParam("pid") String pid) {

		SolrOperation<Customer> slp = new SolrOperation<>();
		Pagination pagination = slp.queryList(1, 10, 3, pid);
		List<LuceneProject> list = pagination.getList();

		List<ButtDetails> projectButtDetailList = ajaxmateProjectView(request, pid);
		// 将已经匹配的demandId设为null，在页面判断
		list.stream().filter(lp -> projectButtDetailList.stream().map(ButtDetails::getProjectNumber)
				.anyMatch(proId -> proId.equals(lp.getProjectId()))).forEach(lp -> lp.setProjectId(null));

		return list;
	}

	public LuceneCustomer returnLuceCustomer(Customer customer) {
		LuceneCustomer luceneCustomer = new LuceneCustomer();

		luceneCustomer.setCustomerId(customer.getPid());

		luceneCustomer.setCustomerNumber("C" + customer.getCustomerNumber());
		luceneCustomer
				.setCustomerSource(getDicSingleWorth(customer.getCustomerSource(), Constant.DICTIONTRY_CUSTOMERSOURCE));// 客户来源

		luceneCustomer.setCustomerType(getDicSingleWorth(customer.getCustomerType(), Constant.DICTIONTRY_CUSTOMERTYPE));

		String researchFieldWorth = getDicCheckboxWorth(customer.getResearchFieldInteger().toString(),
				Constant.DICTIONTRY_PROJECTFIELD);
		luceneCustomer.setResearchField(Stream.of(researchFieldWorth.split(",")).collect(Collectors.toList()));

		luceneCustomer.setArea(getAreaWorth(customer.getArea(), customer.getDomesticOrForeign()));
		luceneCustomer.setCustomerName(customer.getCustomerName());

		luceneCustomer
				.setCustomerNature(getDicSingleWorth(customer.getCustomerNature(), Constant.DICTIONTRY_CUSTOMERNATURE));
		luceneCustomer.setMainBusiness(customer.getMainBusiness());
		luceneCustomer.setMajorNeeds(customer.getMajorNeeds());

		luceneCustomer.setIntentionCooperate2(
				getDicSingleWorth(customer.getIntentionCooperate2(), Constant.DICTIONTRY_INTENTIONCOOPERATE2));
		luceneCustomer.setIntentionCooperate(
				getDicSingleWorth(customer.getIntentionCooperate(), Constant.DICTIONTRY_INTENTIONCOOPERATE));

		luceneCustomer.setCurrentState(getDicSingleWorth(customer.getCurrentState(), Constant.DICTIONTRY_CURRENTSATUS));
		luceneCustomer.setCustomerContact(customer.getCustomerContact());

		if (StringUtil.isEmpty(customer.getCustomerContact())) {
			luceneCustomer.setCustomerContactName("");
		} else {
			luceneCustomer
					.setCustomerContactName(personService.findPersonByPid(customer.getCustomerContact()).getName());
		}

		return luceneCustomer;
	}

	/**
	 * 客户需求列表跳转页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/customerDemandList")
	public String customerDemandList(Customer customer, BindingResult bindingResult, Integer pageNum, Model model) {

		String customerPid = customer.getPid();
		customer = customerService.getById(customerPid);
		// 得到customerNumber
		int customerNumber = customer.getCustomerNumber();

		Demand dem = new Demand();
		dem.setSourceRemark("C" + customerNumber);
		List<Demand> demandList = demandService.queryAll(dem);

		demandList.forEach(demand -> demand
				.setDemandType(getDicCheckboxWorth(demand.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE)));
		demandList.forEach(demand -> demand
				.setDemandStatusWorth(getDicSingleWorth(demand.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS)));

		PageInfo<Demand> pageInfo = new PageInfo<Demand>(demandList);

		model.addAttribute(pageInfo);
		model.addAttribute("customerId", customer.getPid());
		model.addAttribute("customerName", customer.getCustomerName());

		return "customerdemanlist";
	}

	@RequestMapping("/showDemandMatchedProject")
	public String showDemandMatchedProject(Model model, HttpServletRequest request, Demand demand,
			@RequestParam(value = "searchKeyword", required = false) String searchKeyword,
			@RequestParam(value = "demandId", required = false) String demandId,
			@RequestParam(value = "demandNumber", required = false) String demandNumber,
			@RequestParam(value = "demandName", required = false) String demandName,
			@RequestParam("customerId") String customerId) {

		if (StringUtil.isNotEmpty(demandId)) {
			demand.setPid(demandId);
		}

		if (StringUtil.isNotEmpty(demandNumber)) {
			demand.setDemandNumber(Integer.parseInt(demandNumber));
		}
		if (StringUtil.isNotEmpty(demandName)) {
			demand.setDemandName(demandName);
		}

		Customer customer = customerService.getById(customerId);
		model.addAttribute("customer", customer);

		IsolrOperation<LuceneProject> iso = new SolrOperation<>();

		Pagination pa = iso.queryList(1, 10, 6, demand.getPid());
		PageInfo<LuceneProject> pageInfo = new PageInfo<LuceneProject>(pa.getList());
		// pageInfo.set
		pageInfo.setTotal(pa.getTotalCount());
		pageInfo.setPageNum(1);
		pageInfo.setFirstPage(0);
		// Page{count=true, pageNum=1, pageSize=10, startRow=0, endRow=10,
		// total=6, pages=1, countSignal=false, orderBy='null',
		// orderByOnly=false, reasonable=true, pageSizeZero=true}
		addListToModel(model);
		model.addAttribute(pageInfo);
		demand = demandService.getById(demand.getPid());
		model.addAttribute("demand", demand);

		ButtDetails olderButt = new ButtDetails();
		olderButt.setDemandNumber(demand.getPid());
		olderButt.setButtPersonId(getUserId(request));
		olderButt.setFuture(1);
		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
		List<String> searchProjectIdList = pageInfo.getList().stream().map(LuceneProject::getProjectId)
				.collect(Collectors.toList());
		List<String> buttedProjectIdList = historyButtDetails.stream().map(ButtDetails::getProjectNumber)
				.filter(StringUtil::isNotEmpty).filter(projectId -> searchProjectIdList.contains(projectId))
				.collect(Collectors.toList());
		model.addAttribute("buttedProjectIdList", buttedProjectIdList);
		return "customerdemandproject";
	}

	@RequestMapping("/searchMatchedProject2")
	public String searchMatchedProject2(Model model, Project project, String searchKeyword,
			@RequestParam(defaultValue = "1") int pageNo, String demandId, Demand demand, HttpServletRequest request,
			@RequestParam("customerId") String customerId) {
		demand.setPid(demandId);

		Customer customer = customerService.getById(customerId);
		model.addAttribute("customer", customer);

		model.addAttribute("demand", demand);
		PageInfo<Project> searchPageInfo = searchPageInfo(model, project, searchKeyword, pageNo);
		// 根据demandid查询对接详情，然后筛选出已经对接过的project
		ButtDetails olderButt = new ButtDetails();
		olderButt.setDemandNumber(demandId);
		olderButt.setButtPersonId(getUserId(request));
		olderButt.setFuture(1);
		List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
		List<String> searchProjectIdList = searchPageInfo.getList().stream().map(Project::getPid)
				.collect(Collectors.toList());
		List<String> buttedProjectIdList = historyButtDetails.stream().map(ButtDetails::getProjectNumber)
				.filter(StringUtil::isNotEmpty).filter(projectId -> searchProjectIdList.contains(projectId))
				.collect(Collectors.toList());
		model.addAttribute("buttedProjectIdList", buttedProjectIdList);
		return "customerdemandproject";
	}

	@RequestMapping("/hasbeencompared")
	public String hasbeencompared(Model model, HttpServletRequest request, Integer buttSta,@RequestParam(value = "demandNumber", required = false) String demandNumber,
			@RequestParam("customerNumber") String customerNumber, @RequestParam(defaultValue = "1") int pageNo, String customerId) {

		Demand demand = new Demand();
		demand.setSourceRemark("C" + customerNumber);
		List<Demand> demandList = demandService.queryAll(demand);
		
		String [] demandIdArr=new String[demandList.size()];
		
		for (int i = 0; i < demandList.size(); i++) {
			String demandId=demandList.get(i).getPid();
			demandIdArr[i]=demandId;
		}
		
		ButtDetails button=new ButtDetails();
		button.setInButtDetails(demandIdArr);
		//button.setButtPersonId(getUserId(request));
		
		
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<ButtDetails> buttonList=detailsService.queryInButtDetails(button);
		if(StringUtil.isNotEmpty(demandNumber)){
			buttonList=buttonList.stream().filter(bd -> bd.getDemandNumber().equals(demandNumber)).collect(Collectors.toList());
		}
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(buttonList);
		pageInfo.getList().forEach(bd -> bd.setButtStatusWorth(getDicCheckboxWorth(bd.getButtStatus().toString(), Constant.DICTIONTRY_BUTTSTATUS)));
		
		List<Dictiontry> buttStatusList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		model.addAttribute("buttStatusList", buttStatusList);
		model.addAttribute("demandBuList", demandList);
		model.addAttribute("customerNumber", customerNumber);
		model.addAttribute("demandNumber", demandNumber);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("buttSta", buttSta != null ? buttSta.toString() : "");
		model.addAttribute("customerId", customerId);
		return "showDemandButtedDetail2";
	}

	@ResponseBody
	@RequestMapping("/queryProjectButtDetail")
	public List<ButtDetails> queryProjectButtDetail(String demandId, HttpServletRequest request, Integer buttSta) {
		ButtDetails buttDetails = new ButtDetails();
		buttDetails.setButtPersonId(getUserId(request));
		buttDetails.setDemandNumber(demandId);
		buttDetails.setFuture(1);
		buttDetails.setButtStatus(buttSta);
		buttDetails.setProjectNumberEmpty(false);
		List<ButtDetails> demandDetailList = detailsService.findButtDetails(buttDetails);
		demandDetailList.forEach(bd -> bd.setButtStatusWorth(
				getDicCheckboxWorth(bd.getButtStatus().toString(), Constant.DICTIONTRY_BUTTSTATUS)));
		demandDetailList.forEach(bd -> bd.setRemark2(bd.getDemandName() + "<br>" + bd.getProjectName()));
		return demandDetailList;
	}
	
	
	  private static ArrayList<ButtDetails> removeDuplicateUser(List<ButtDetails> users) {
	        Set<ButtDetails> set = new TreeSet<ButtDetails>(new Comparator<ButtDetails>() {
	            @Override
	            public int compare(ButtDetails o1, ButtDetails o2) {
	                //字符串,则按照asicc码升序排列
	                return o1.getDemandNumber().compareTo(o2.getDemandNumber());
	            }
	        });
	        set.addAll(users);
	        return new ArrayList<ButtDetails>(set);
	    }

		
		
		/**
		 * 进入修改页面
		 * @return
		 */
		@RequestMapping(value= "updateView",produces="application/json;charset=UTF-8")
		public String updateView(@RequestParam("pid") String pid,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "customerId", required = false) String customerId){
			//调用本类方法
			addListToModel(model);
			
			//通过pid查询专家表
			Person person = personService.findPersonByPid(pid);
			
			String cityId = "";
			String province = "";
			String areaId = String.valueOf(person.getArea());
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
				// 说明是区的id
				// 截取得到省和市的id
				cityId = areaId.substring(0, 5);
				province = areaId.substring(0, 2);
				model.addAttribute("areaId", areaId);
				model.addAttribute("cityId", cityId);
				model.addAttribute("province", province);
			}
			if (areaId.length() < 3 && areaId.length() > 0) {
				// 说明是省的id
				model.addAttribute("province", areaId);
			}
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
				// 说明是市的id
				// 截取得到省和市的id
				cityId = areaId;
				province = areaId.substring(0, 2);
				model.addAttribute("province", province);
				model.addAttribute("cityId", cityId);
			}

			if (person.getDomesticOrForeign() == 1) {
				model.addAttribute("countryId", Integer.parseInt(areaId));
			}
			
			// 所有省份
			List<Dictiontry> provinceDictiontryList = getAreaProvince();
			// 所有市
			List<Dictiontry> cityDictiontryList = getCityByProvince(province);
			// 所有区
			List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
			
			// 所属领域二进制转化为字符串并存放到数组中
			String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
			model.addAttribute("researchFieldArr", researchFieldArr);
			// 人才级别二进制转化为字符串并存放到数组中
			if (person.getTalentLevel() != null) {
				String[] talentLevelFieldArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
				model.addAttribute("talentLevelFieldArr", talentLevelFieldArr);
			}else {
				model.addAttribute("talentLevelFieldArr", "");
			}
			
			model.addAttribute("person",person);
			model.addAttribute("provinceDictiontryList", provinceDictiontryList);
			model.addAttribute("cityDictiontryList", cityDictiontryList);
			model.addAttribute("areaDictiontryList", areaDictiontryList);
			
			model.addAttribute("origType", origType);
			model.addAttribute("customerId", customerId);
			
			return "customerUpdateContact";
		}
		
		
	/**
	 * 下载详情附件
	 */
	@RequestMapping("/download")
	@ResponseBody
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) {

		List<String> tagList = new ArrayList<>();
		List<List<String>> contentLists = Collections.synchronizedList(new ArrayList<List<String>>());
		tagList.add("客户ID");
		tagList.add("客户名称");
		tagList.add("客户性质");
		tagList.add("主要需求");
		tagList.add("当前合作状态");
		tagList.add("录入人");
		tagList.add("最新进展");
		
		List<Customer> customerList=customerService.queryAll(new Customer());
		for (Customer customer : customerList) {
			List<String> content = new ArrayList<>();
			content.add("C"+customer.getCustomerNumber());
			content.add(customer.getCustomerName());
			content.add(getDicSingleWorth(customer.getCustomerNature(), Constant.DICTIONTRY_CUSTOMERNATURE));
			content.add(customer.getMajorNeeds());
			content.add(getDicSingleWorth(customer.getCurrentState(), Constant.DICTIONTRY_CURRENTSATUS));
			content.add(userService.getById(customer.getCollectPersonId()).getFullName());
			String evolve =customer.getEvolve();
			if(evolve!=null&&!"".equals(evolve)){
				
				String ev[]=evolve.split("#");
				if(ev.length>3){
					content.add(ev[0]+"#"+ev[1]+"#"+ev[2]);
				}else{
					content.add(evolve);
				}
			}else{
				content.add(customer.getEvolve());
			}
			
			contentLists.add(content);
		}
		//下载excel至服务器
		File file=ExcelUtil.writeExcel(tagList, contentLists,"customerList.xls");
		//将服务器上文件下载至本地
		try {
			ExcelUtil.downLoad(request, file, response);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	@RequestMapping(value = "/showselectperson")
	public String showselectperson(@RequestParam(value = "personName", required = false) String personName,@RequestParam("customerId") String customerId,Model model,HttpServletRequest request) {

	
		Person person=new Person();
		person.setName(personName);
		List<Person>personList=personService.findMPersonList(person);

		if(personList.size()<1){
			return "testshowselectperson";
		}
		model.addAttribute("personList", personList);
		return "showselectperson";
	}
	
	/**
	 * xyx
	 * @param checkStr personId
	 * @param model
	 * @param request
	 * @return
	 * 2018年10月26日
	 */
	@RequestMapping(value = "/returnCheckperson", method = RequestMethod.GET)
	@ResponseBody
	public Person returnCheckperson(@RequestParam(value = "checkStr", required = false) String checkStr,@RequestParam(value = "customerId") String customerId, Model model,HttpServletRequest request) {

		Person person=personService.findPersonByPid(checkStr);
		
		
		return person;
	}
	
	/**
	 * 把Person转换为LucenePerson
	 * @author dongli
	 * @date 2018年9月21日
	 * @param person
	 * @return
	 */
	public LucenePerson lucenePersonConversion(Person person){
		LucenePerson lp = new LucenePerson();
		try{
			//pid
			String expertId = person.getPid();
			if(expertId!=null&&!"".equals(expertId)){
				lp.setExpertId(expertId);
			}
			//专家id
			Integer expertNumber = person.getExpertNumber();
			if(expertNumber!=null&&expertNumber>0){
				lp.setExpertNumber("E"+expertNumber);
			}
			//专家来源
			Integer source = person.getSource();
			if(source!=null&&source>0){
				lp.setSource(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
			}
			//专家类型
			Integer type = person.getType();
			if(type!=null && type>0){
				lp.setType(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
			}
			/**
			 * 所属领域
			 */
			String researchField = person.getResearchField();
			if(researchField!=null &&!"".equals(researchField)){
				researchField = getDicCheckboxWorth(person.getResearchFieldInteger().toString(), Constant.DICTIONTRY_PROJECTFIELD);
				String[] arr  = researchField.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setResearchField(list);
			}
			//地区
			String	area =person.getArea();
			if(area!=null&&!"".equals(area)){
				lp.setArea(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
			}
			/**
			 * 人才级别
			 */
			String	talentLevel =person.getTalentLevel();
			if(talentLevel!=null&&!"".equals(talentLevel)){
				talentLevel = getDicCheckboxWorth(person.getTalentLevelInteger().toString(), Constant.DICTIONTRY_TALENTLEVEL);
				String[] arr  = talentLevel.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setTalentLevel(list);
			}
			//姓名
			String	name = person.getName();
			if(name!=null&&!"".equals(name)){
				lp.setName(name);
			}
			//毕业院校及所学专业
			String	schoolAndMajor =person.getSchoolAndMajor();
			if(schoolAndMajor!=null&&!"".equals(schoolAndMajor)){
				lp.setSchoolAndMajor(schoolAndMajor);
			}
			//单位
			String	unit = person.getUnit();
			if(unit!=null&&!"".equals(unit)){
				lp.setUnit(unit);
			}
			//职务(职称)
			String	title = person.getTitle();
			if(title!=null&&!"".equals(title)){
				lp.setTitle(title);
			}
			//专业领域
			String	professionaField =person.getProfessionaField();
			if(professionaField!=null&&!"".equals(professionaField)){
				lp.setProfessionaField(professionaField);
			}
			//教育背景
			String	education =person.getEducation();
			if(education!=null&&!"".equals(education)){
				lp.setEducation(education);
			}
			//工作经历
			String	workExp =person.getWorkExp();
			if(workExp!=null&&!"".equals(workExp)){
				lp.setWorkExp(workExp);
			}
			//荣誉奖励
			String	honorAward =person.getHonorAward();
			if(honorAward!=null&&!"".equals(honorAward)){
				lp.setHonorAward(honorAward);
			}
			//科技成果
			String	technica = person.getTechnica();
			if(technica!=null&&!"".equals(technica)){
				lp.setTechnica(technica);
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return lp;
	}
	
	@RequestMapping("/detailStatistics")
	public String detailStatistics(String beginDate, String endDate, String userId, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Customer> list = customerService.detailStatistics(beginDate, endDate, userId);
		PageInfo<Customer> pageInfo = new PageInfo<>(list);
		List<User> userList = userService.queryInPidList(pageInfo.getList().stream().map(Customer::getCollectPersonId).distinct().collect(Collectors.toList()));
		pageInfo.getList().forEach(cus -> {
			cus.setCollectPersonId(userList.stream().filter(user -> cus.getCollectPersonId().equals(user.getPid())).map(User::getFullName).findAny().get());
			cus.setCurrentStateName(getDicSingleWorth(cus.getCurrentState(), Constant.DICTIONTRY_CURRENTSATUS));
		});
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_customer", true);
		model.addAttribute("route", "/customer");
		return "detailStatistics";
	}
	
	@RequestMapping("/updateDetailStatistics")
    public String updateDetailStatistics(String beginDate, String endDate, String userId, Integer operaIndex, String fullname, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
    	List<String> refPidList = queryUpdateLog(beginDate, endDate, userId, operaIndex);
    	PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Customer> list = customerService.queryInPidList(refPidList);
		PageInfo<Customer> pageInfo = new PageInfo<>(list);
		pageInfo.getList().forEach(cus -> {
			cus.setCollectPersonId(fullname);
			cus.setCurrentStateName(getDicSingleWorth(cus.getCurrentState(), Constant.DICTIONTRY_CURRENTSATUS));
		});
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_customer", true);
		model.addAttribute("route", "/customer");
		return "detailStatistics";
    }
	
	
	@RequestMapping(value = "/importcustomer")
	public String importcustomer(Customer customer, BindingResult bindingResult, Integer pageNum, Model model,
			@RequestParam(value = "customerNumberId", required = false) String customerNumberId,HttpServletRequest request) {

		

		// 收集人(录入人) 从session中获取登录账号
		String loginId=getUserInfoBySession(request).getUserId();
		customer.setCollectPersonId(loginId);
		
		User user2 =userService.getById(loginId);
		model.addAttribute("user2", user2);
		
		String cityId = "";
		String province = "";
		
		//通过pid查询用户
	    User user = userService.findUserById(customer.getCollectPersonId());

		if (StringUtil.isNotEmpty(customer.getArea()) && customer.getDomesticOrForeign() != null) {
			areaModel(model, customer.getArea(), customer.getDomesticOrForeign());
		}

		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		addListToModel(model);
		String customerNum = "";
		if (StringUtil.isNotEmpty(customer.getMajorNeeds())) {
			customer.setMajorNeeds(customer.getMajorNeeds().trim());
		}

		if (StringUtil.isNotEmpty(customer.getCustomerName())) {
			customer.setCustomerName(customer.getCustomerName().trim());
		}
		// 重新复制客户id
		if (StringUtil.isNotEmpty(customerNumberId)) {
			customerNum = String.valueOf(customerNumberId.trim());
			// 去除字母
			customerNum = customerNum.replaceAll("[a-zA-Z]", "");
		}

		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(customer.getResearchField())) {
			researchFieldArr = customer.getResearchField().split(",");
			customer.setResearchFieldNumber(researchFieldArr.length);
			customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));
		}
		model.addAttribute("researchFieldArr", researchFieldArr);
		if (StringUtil.isNotEmpty(customerNum)) {
			customer.setCustomerNumber(Integer.parseInt(customerNum));
		}
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		// 查询所有会议活动数据
		List<Customer> customerList = customerService.queryAllCustomer(customer);

		for (int i = 0; i < customerList.size(); i++) {
			String areaStr = "";
			String reachName = "";
			// 得到所属领域二进制
			String rearch = customerList.get(i).getResearchField();
			// 得到areaId
			String areaStrId = String.valueOf(customerList.get(i).getArea());
			if (areaStrId != null && !"".equals(areaStrId) && !"null".equals(areaStrId)) {
				if (areaStrId.length() < 10 && areaStrId.length() > 5 && areaStrId.length() != 4) {
					// 说明是区的id
					// 截取得到省和市的id
					Dictiontry dicArea = new Dictiontry();
					dicArea.setNames(areaStrId);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
					// 区的名字
					// areaStr =
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// cityId = areaStrId.substring(0, 5);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					// dicArea.setNames(cityId);
					// // 市的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// province = areaStrId.substring(0, 2);
					// dicArea.setNames(province);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// // 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";

					areaStr = getAreaWorth(areaStrId, 0);
				}

				if (areaStrId.length() == 4) {
					// 说明是国外的
					Dictiontry dicArea = new Dictiontry();
					dicArea.setPid(Integer.parseInt(areaStrId));
					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
					// 省的名字
					areaStr=getAreaWorth(areaStrId, 1);
				}
				if (areaStrId.length() < 6 && areaStrId.length() > 2 && areaStrId.length() != 4) {
					// 说明是市的id
					Dictiontry dicArea = new Dictiontry();
					cityId = areaStrId.substring(0, 5);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					dicArea.setNames(cityId);
					// 市的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + " ";
					//
					// province = areaStrId.substring(0, 2);
					// dicArea.setNames(province);
					// dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// // 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";
					areaStr = getAreaWorth(areaStrId, 0);

				}

				if (areaStrId.length() < 3 && areaStrId.length() > 0 && areaStrId.length() != 4) {
					// 说明是省的id
					Dictiontry dicArea = new Dictiontry();
					province = areaStrId.substring(0, 2);
					dicArea.setNames(province);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					// areaStr +=
					// dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth()
					// + "";
					areaStr = getAreaWorth(areaStrId, 0);
				}
			}
			// 给地区附上名字
			customerList.get(i).setAreaNameStr(areaStr);
			// String rearchStr = StrUtil.byteToString(rearch);
			reachName = getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
			
			String personId=customerList.get(i).getCollectPersonId();
			if(StringUtil.isNotEmpty(personId)){
				customerList.get(i).setRemark5(userService.getById(personId).getFullName());
			}
			
			// String[] reaArray = rearchStr.split(",");
			// for (String reaStr : reaArray) {
			// Dictiontry dic = new Dictiontry();
			// dic.setGroupName(Constant.DICTIONTRY_PROJECTFIELD);
			// dic.setNames(reaStr);
			// List<Dictiontry> dicList =
			// dictiontryService.findDictiontryByNamesAndGroupName(dic);
			// for (Dictiontry dictiontry : dicList) {
			// reachName += dictiontry.getWorth() + " ";
			// }
			// }
			customerList.get(i).setResearchFieldNameStr(reachName);
			// 取出当前客户性质
			int customerNatureStr = customerList.get(i).getCustomerNature();
			// 取出当前合作状态
			int currentStateStr = customerList.get(i).getCurrentState();
			customerList.get(i)
					.setCustomerNatureName(getDicSingleWorth(customerNatureStr, Constant.DICTIONTRY_CUSTOMERNATURE));
			customerList.get(i)
					.setCurrentStateName(getDicSingleWorth(currentStateStr, Constant.DICTIONTRY_CURRENTSATUS));
		}

		  //查询已经关注的
        Subscribe subscribe = new Subscribe();
        subscribe.setSubType(3);//关注类型为会议
        subscribe.setUserid(getUserId(request));
        List<Subscribe> subList = subscribeService.queryAll(subscribe);
        List<String> subDemandIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
        model.addAttribute("subDemandIdList", subDemandIdList);

		// 将list放进PageInfo
		PageInfo<Customer> pageInfo = new PageInfo<Customer>(customerList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("user", user);

		// 演讲嘉宾展示List
		return "showImportCustomer";
	}
	
	
	/**
	 * 修改方法
	 * @return
	 */
	@Log("修改客户联系人")
	@RequestMapping(value= "saveCustomerContact",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
	public String saveCustomerContact(@RefPid @Valid Person person,BindingResult bindingResult,@RequestParam("annex1") MultipartFile annex1,
			HttpServletRequest req,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "conferencePid", required = false) String conferencePid,@RequestParam(value = "customerId", required = false) String customerId){
		
		//重新选择附件并上传
		if (!annex1.isEmpty() && annex1 != null) {
			// 文件名字
			String fileName = annex1.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("person", fileName);
			person.setAnnex(oldFileName);
			try {
				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}else {
			//当附件为空的时候不改变原来附件的内容
			String fileName = FileUtils.transferTo(Constant.DEF_PERSON_PATH, annex1, "person");
			Person per = personService.getById(person.getPid());
			fileName = StringUtil.isEmpty(fileName) ? per.getAnnex() : fileName ;
			person.setAnnex(fileName);
		}
		
		//表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("person", person);
				return updateView(person.getPid(),model,null,null);
			}
		}
		
		//设置最新更新时间
		person.setUpdateTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
		
		//判断联系方式是否有改变，如果没有就将原来的值赋给它
		Person per2 = personService.getById(person.getPid());
		String fixedPhone = person.getFixedPhone();  //固定电话
		String tell = person.getTell();  //手机
		String email = person.getEmail();  //邮箱
		String wechat = person.getWechat();  //微信
		String otherContact = person.getOtherContact();  //其他联系方式
		if (StringUtil.isNotEmpty(fixedPhone) && fixedPhone.contains("*")) {
			person.setFixedPhone(per2.getFixedPhone());
		}
		if (StringUtil.isNotEmpty(tell) && tell.contains("*")) {
			person.setTell(per2.getTell());
		}
		if (StringUtil.isNotEmpty(email) && email.contains("*")) {
			person.setEmail(per2.getEmail());
		}
		if (StringUtil.isNotEmpty(wechat) && wechat.contains("*")) {
			person.setWechat(per2.getWechat());
		}
		if (StringUtil.isNotEmpty(otherContact) && otherContact.contains("*")) {
			person.setOtherContact(per2.getOtherContact());
		}
		
		// 转化为二进制保存
		person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		if (person.getTalentLevel() != null) {
			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
		}
		
		person.setExpertNumber(null);
		
		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
		if (!hasContact(person)) {
            model.addAttribute("alert", "至少填写一种联系方式");
            return updateView(person.getPid(),model,null,null);
        } 
		
		//查出客户信息
		Customer customer =customerService.getById(customerId);
		List<Person> personList=personService.queryByContactAndName(person);
		
		if (personList.size()>0) {
        	//大于0说明person表中有该条专家信息，则替换外键
			customer.setCustomerContact(personList.get(0).getPid());
			
			// 转化为二进制保存
			customer.setResearchFieldInteger(StrUtil.stringByByte(customer.getResearchField()));
			
        	customerService.update(customer);
        	
        	LuceneCustomer lucustomer = returnLuceCustomer(customer);
    		IsolrOperation<LuceneCustomer> iso = new SolrOperation<>();
    		iso.update("customer", lucustomer);
        }else{
        	//没有该条专家信息则保存
        	saveCustomerGuest(customerId, person, bindingResult, model, annex1, req);
        }
		
		//调用本类方法
		addListToModel(model);
		
		//跳转页面
		if("333".equals(origType) && StringUtil.isNotEmpty(customerId)){
			return "redirect:/customer/customerList";
		}else if(StringUtil.isNotEmpty(customerId) && "222".equals(origType)){
			return "redirect:/customer/showDetail?customerId=" + customerId;
		}else if(StringUtil.isNotEmpty(origType) && !"222".equals(origType) ){
			return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
		}else{
			//修改后跳转到专家管理页面
//			return "redirect:/person/findPersonList";
			//修改后跳转到专家详情页面
			return "redirect:/person/personDetails?pid="+person.getPid();
		}
	}
	
}
